中止/取消从ActionFilter行动和反应的最佳方法 [英] Best way to abort/cancel action and response from ActionFilter

查看:689
本文介绍了中止/取消从ActionFilter行动和反应的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

中止/取消从ActionFilter行动最好的办法

Best way to abort/cancel action from ActionFilter

我这有 ActionFilter ,它的假设立即断开连接并返回401 Unauthroized:

I've got this ActionFilter, and it's suppose to end the connection immediately and return a 401 Unauthroized:

public class SignInRequired : ActionFilterAttribute 
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // User is verified, continue executing action

        if (Acme.Web.CurrentUser != null)
        {
            return;
        }

        // End response with 401 Unauthorized

        var response = HttpContext.Current.Response;
        response.StatusCode = (int)HttpStatusCode.Unauthorized;
        response.End();

        // Prevent the action from actually being executed

        filterContext.Result = new EmptyResult();
    }
}

我学会了如何你可以通过设置'context.Result =新EmptyResult()`的这里,但我不知道这是冲洗反应和关闭连接的最佳方式。

I learned how you can cancel the action from executing by setting 'context.Result = new EmptyResult()` here, but I'm not sure if this is the best way to flush the response and close the connection.

推荐答案

设置响应将意味着动作不会被调用。

Setting the response will mean the action doesn't get called.

public override void OnActionExecuting(HttpActionContext actionContext)    
{ 
    actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
}

至于其他的答案说,虽然,验证应与AuthorizeAttribute(文档的为Web.API 或的为MVC )。

这篇关于中止/取消从ActionFilter行动和反应的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆