3

アクションの実際の実行をバイパスして値を返す ActionFilterAttribute を作成できますか?

4

2 に答える 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 に答える