ActionFilterAttribute - 适用于特定控制器类型的操作 [英] ActionFilterAttribute - apply to actions of a specific controller type
问题描述
我正在使用 ActionFilterAttribute 来执行自定义身份验证逻辑.该属性将仅用于包含我的身份验证逻辑的派生 Controller 类.
I'm using an ActionFilterAttribute to do custom authentication logic. The Attribute will only be used on a derived Controller class that contains my authentication logic.
这是我的控制器,派生自我的自定义控制器类和一个示例属性:
Here's my Controller, derived from my custom controller class, and a sample attribute:
public class MyController : CustomControllerBase
{
[CustomAuthorize(UserType = UserTypes.Admin)]
public ActionResult DoSomethingSecure()
{
return View();
}
}
这是我的 ActionFilterAttribute 示例:
Here's an example of my ActionFilterAttribute:
public class CustomAuthorizeAttribute : ActionFilterAttribute
{
public MyUserTypes UserType { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
myUser user = ((CustomControllerBase)filterContext.Controller).User;
if(!user.isAuthenticated)
{
filterContext.RequestContext.HttpContext.Response.StatusCode = 401;
}
}
}
效果很好.
问题是:我可以要求此属性仅用于我的自定义控制器类型中的操作吗?
Here's the question: Can I demand that this attribute ONLY be used on Actions in my custom controller type?
推荐答案
您可以将 ActionFilter 放在类本身上.类中的所有动作都会实现ActionFilter.
You can put the ActionFilter on the class itself. All actions in the class will realize the ActionFilter.
[CustomAuthorize]
public class AuthorizedControllerBase : CustomControllerBase
{
}
public class OpenAccessControllerBase : CustomControllerBase
{
}
public class MyRealController : AuthorizedControllerBase
{
// GET: /myrealcontroller/index
public ActionResult Index()
{
return View();
}
}
这篇关于ActionFilterAttribute - 适用于特定控制器类型的操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!