如何添加 .Net MVC 请求过滤器以防止基于角色成员资格的操作调用?

How to add a .Net MVC request filter to prevent action calls based on role membership?

在 .Net MVC5 中,如何添加请求过滤器以防止基于角色成员资格的操作调用?

this评论:

wouldn't it make more sense to use a request filter to prevent the action call on the controller in the event that the current user did not have the right role membership instead of trying to mix the auth logic in to the business logic?

谢谢。

我对此的最佳解决方案是使用: [授权属性]

您可以将其作为 c# mvc 中使用的普通属性,例如 ex:

 [Authorize]
 public ActionResult AuthenticatedUsers()
 {
     return View();
 }

您也可以像这样在控制器顶部使用它:

[Authorize]
 public class HomeController : Controller
 {
 }

如果你想让它依赖于角色,你只需简单地给这个属性一个参数,就像这样:

[Authorize(Roles = "Admin, Super User")]
 public ActionResult AdministratorsOnly()
 {
     return View();
 }

 [Authorize(Users = "Betty, Johnny")]
 public ActionResult SpecificUserOnly()
 {
     return View();
 }

Here 是针对您的问题的一些更详细的信息,我建议这些信息会对您有很大帮助。

祝你好运!