SONY DSC

在 ASP.NET MVC 中,通常會有對某些 Controller 底下的 Action 做 log 或是過濾 Request 的需求,而 ActionFilter 可以滿足這樣的需求,它是一個 Attribute,實作它之後只要宣告在 Action 上即可。

ActionFilter 有四個 method,分別是 OnActionExecuted、OnActionExecuting、OnResultExecuted、OnResultExecuting,而它的執行順序則是:

  1. OnActionExecuting
  2. Controller's action
  3. OnActionExecuted
  4. OnResultExecuting
  5. View binding
  6. OnResultExecuted

假設今天我要在某個 Action 中檢查 request 是否為 POST,是的話在 TempData 中塞資料,否則導回首頁,那程式碼可以這樣寫:

public class TokenValidationActionAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.HttpContext.Request.HttpMethod == HttpMethods.POST)
        {
            filterContext.Controller.TempData["aaa3"] = "aaa3";
        }

        UrlHelper urlHelper = new UrlHelper(filterContext.RequestContext);
        filterContext.Result = new RedirectResult(urlHelper.Action("About", "Home"));
    }

}

實作之後,宣告在 Action 上方:

[TokenValidationAction]
public ActionResult TestAction()

很簡單卻很實用的 Attribute。

arrow
arrow
    文章標籤
    C#
    全站熱搜

    卑微研究生 發表在 痞客邦 留言(0) 人氣()