开发者

How do you interrupt/intercept MVC Actions using ActionFilters?

Feel free to close t开发者_开发技巧his one if it s a duplicate. I couldn't find an answer.

I wish to be able to place a System.Web.ActionFilterAttribute on an Action Method and override the OnActionExecuting method to insert business logic which determines if the Action should be fulfilled.

Can the ActionExecutingContext be used to cancel the executing Action Method and do one of the following:

  • Send an HTTP Status Code (and the corresponding <customError> page).
  • Execute a different Action Method within the same Controller.


Send an HTTP Status Code (and the corresponding <customError> page)

Almost:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    filterContext.HttpContext.Response.StatusCode = 500;
}

Execute a different Action Method within the same Controller.

Yes:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    filterContext.Result = new ViewResult() { ViewName = "SomeOtherAction" };
}


You can always redirect to another controller/action in an action filter.

See here for an example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜