asp.net-mvc 如何从 ActionFilter 跳过动作执行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9837180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:49:08  来源:igfitidea点击:

How to skip action execution from an ActionFilter?

asp.net-mvcaction-filter

提问by user49126

Is it possible to skip the whole action method execution and return a specific ActionResultwhen a certain condition is met in OnActionExecuting?

是否可以跳过整个操作方法执行并ActionResult在满足特定条件时返回特定的OnActionExecuting

采纳答案by tpeczek

You can use filterContext.Result for this. It should look like this:

您可以为此使用 filterContext.Result 。它应该是这样的:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    //Check your condition here
    if (true)
    {
        //Create your result
        filterContext.Result = new EmptyResult();
    }
    else
        base.OnActionExecuting(filterContext);
}

回答by RickAndMSFT

See my download sample and MSDN article Filtering in ASP.NET MVC.

请参阅我的下载示例和 MSDN 文章Filtering in ASP.NET MVC

You can cancel filter execution in the OnActionExecutingand OnResultExecutingmethods by setting the Resultproperty to a non-null value.

您可以通过将属性设置为非空值来取消OnActionExecutingOnResultExecuting方法中的过滤器执行Result

Any pending OnActionExecutedand OnActionExecutingfilters will not be invoked and the invoker will not call the OnActionExecutedmethod for the cancelled filter or for pending filters.

不会调用任何挂起OnActionExecutedOnActionExecuting过滤器,并且调用者不会调用OnActionExecuted已取消过滤器或挂起过滤器的方法。

The OnActionExecutedfilter for previously run filters will run. All of the OnResultExecutingandOnResultExecutedfilters will run.

OnActionExecuted先前运行的过滤器的过滤器将运行。所有OnResultExecutingandOnResultExecuted过滤器都将运行。

The following code from the sample shows how to return a specific ActionResultwhen a certain condition is met in OnActionExecuting:

示例中的以下代码显示了如何在ActionResult满足特定条件时返回特定值OnActionExecuting

if (filterContext.RouteData.Values.ContainsValue("Cancel")) 
{
    filterContext.Result = new RedirectResult("~/Home/Index");
    Trace.WriteLine(" Redirecting from Simple filter to /Home/Index");
}

回答by Mehul Vaghela

You can use the following code here.

您可以在此处使用以下代码。

public override void OnActionExecuting(ActionExecutingContext filterContext)
 {
    ...
    if (needToRedirect) //your condition here
    {
       ...
       filterContext.Result = new RedirectToAction(string action, string controller)
       return;
    }
    ...
 }

RedirectToAction will redirect you the specific action based on the condition.

RedirectToAction 将根据条件重定向您的特定操作。

回答by Anup Sharma

If anyone is extending ActionFilterAttributein MVC 5 API, then you must be getting HttpActionContextinstead of ActionExecutingContextas the type of parameter. In that case, simply set httpActionContext.Responseto new HttpResponseMessageand you are good to go.

如果有人ActionFilterAttribute在 MVC 5 API 中进行扩展,那么您必须获取HttpActionContext而不是ActionExecutingContext作为参数类型。在这种情况下,只需设置httpActionContext.Response为 newHttpResponseMessage就可以了。

I was making a validation filter and here is how it looks like:

我正在制作一个验证过滤器,它是这样的:

    /// <summary>
    /// Occurs before the action method is invoked.
    /// This will validate the request
    /// </summary>
    /// <param name="actionContext">The http action context.</param>
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        ApiController ctrl = (actionContext.ControllerContext.Controller as ApiController);
        if (!ctrl.ModelState.IsValid)
        {
            var s = ctrl.ModelState.Select(t => new { Field = t.Key, Errors = t.Value.Errors.Select(e => e.ErrorMessage) });
            actionContext.Response = new System.Net.Http.HttpResponseMessage()
            {
                Content = new StringContent(JsonConvert.SerializeObject(s)),
                ReasonPhrase = "Validation error",
                StatusCode = (System.Net.HttpStatusCode)422
            };
        }
    }