Can I create an ActionFilterAttribute that bypasses the actual execution of the action and returns a value for it?
问问题
4039 次
2 回答
6
对的,这是可能的。您可以设置在覆盖时提供给您的过滤器上下文的OnActionExecuting
结果ActionFilterAttribute
。
using System.Web.Mvc;
public sealed class SampleFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting( ActionExecutingContext filterContext )
{
filterContext.Result = new RedirectResult( "http://google.com" );
}
}
在源代码中,您可以看到设置Result
过滤器上下文的属性会更改流程。
来自 System.Web.Mvc.ControllerActionInvoker:
internal static ActionExecutedContext InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func<ActionExecutedContext> continuation)
{
filter.OnActionExecuting(preContext);
if (preContext.Result != null)
{
return new ActionExecutedContext(preContext, preContext.ActionDescriptor, true /* canceled */, null /* exception */)
{
Result = preContext.Result
};
}
// other code ommitted
}
于 2013-08-23T20:55:15.823 回答
2
你可以像这样:
1)重定向到一些动作,然后返回一些值:
public class MyFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
/*If something happens*/
if (/*Condition*/)
{
/*You can use Redirect or RedirectToRoute*/
filterContext.HttpContext.Response.Redirect("Redirecto to somewhere");
}
base.OnActionExecuting(filterContext);
}
}
2)将一些值直接写入请求并结束它发送给客户端:
public class MyFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
/*If something happens*/
if (/*Condition*/)
{
filterContext.HttpContext.Response.Write("some value here");
filterContext.HttpContext.Response.End();
}
base.OnActionExecuting(filterContext);
}
}
于 2013-08-23T20:56:39.453 回答