果然下午腦子不好,好幾次了,忙了一下午沒看懂,早上一來,沒過多久就弄清楚了。嚶嚶嚶~~
因為以前接觸java的時候filter chain超好用嘛,以至于差點忽略的它的存在,直到我看到.net這邊每個controller里面的每個action都需要判定session的存在,真的好煩好煩,而且還擔心忘記,出現好幾次了,同事的代碼沒寫,跑起來偶爾出錯,不是什么大事兒,但是時不時戳你一下就是煩啊。
安利google和SO,昨天第一次在SO答題,好興奮,哈哈。好了,收!
Attribute感覺是自定義注解的形式。
Attribute分類如下:
Authorization filter, which makes security decisions about whether to execute an action method, such as performing authentication or validating properties of the request. The AuthorizeAttribute class is one example of an authorization filter.
Action filter, which wraps the action method execution. This filter can perform additional processing, such as providing extra data to the action method, inspecting the return value, or canceling execution of the action method.
Result filter, which wraps execution of the ActionResult object. This filter can perform additional processing of the result, such as modifying the HTTP response. The OutputCacheAttribute class is one example of a result filter.
Exception filter, which executes if there is an unhandled exception thrown somewhere in action method, starting with the authorization filters and ending with the execution of the result. Exception filters can be used for tasks such as logging or displaying an error page. The HandleErrorAttribute class is one example of an exception filter.
attribute分類的文檔
看完Authorization filter的描述以后,我們要的是它啦!
廢話不多說,上代碼!
public class AdminAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
HttpSessionStateBase session = filterContext.HttpContext.Session;
Controller controller = filterContext.Controller as Controller;
if (controller != null)
{
if (session != null && (session["admin"] as Admin) == null)
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new {controller = "Admin", action = "Login"}));
}
}
}
}
Action filter其實也是類似的寫法,繼承ActionFilterAttribute,重寫里面的OnActionExecuted(ActionExecutedContext)
OnActionExecuting(ActionExecutingContext)
Called by the ASP.NET MVC framework before the action method executes.
OnResultExecuted(ResultExecutedContext)
OnResultExecuting(ResultExecutingContext)
你需要的方法就好啦!其實看看OnActionExecuting是before method executes的話,重寫這個方法也是可以達到這個效果的啦!只是從語義和這幾個的設計分類來看,Authorize還是更合適一點。另外OnActionExecuted我感覺也可以用來打log。省事兒。
是不是很簡單!!!虧我昨天還死死的翻文檔,翻SO都找不到可行方案,覺得自己蠢爆了!!!這個故事告訴本寶,早上效率高,早上班早下班,對身體生活工作都好!
好了,貼幾個參考吧,畢竟翻了好多東西。
Filtering in ASP.NET MVC
Creating Custom Action Filters
create the authorize filter with parameter asp.net mvc
Override global authorize filter in ASP.NET Core MVC 1.0
Asp.net MVC4: Authorize on both controller and action
Redirect From Action Filter Attribute