返回状态代码未经授权在WebAPI中自定义IActionFilter

Sle*_*lee 22 action-filter asp.net-mvc-4 asp.net-web-api

我正在使用asp.net WebAPI,我需要创建一个自定义ActionFilter,它会快速检查请求URI的用户是否真的能够获取数据.

他们已被授权通过基本身份验证使用Web服务,并且他们的角色已通过自定义角色提供程序进行验证.

我需要做的最后一件事是检查他们是否有权使用URI中的参数查看他们请求的数据.

这是我的代码:

public class AccessActionFilter : FilterAttribute, IActionFilter
    {

        public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken, Func<System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>> continuation)
        {

            var result = //code to see if they have permission returns either 0 or 1

            if (result==0) {
               throw new ArgumentException("You do not have access to this resource");
            }
            return continuation();
        }
    } 
Run Code Online (Sandbox Code Playgroud)

目前我只是抛出一个不是我想要的错误,我宁愿回来,System.Net.HttpStatusCode.Unauthorized但我对我压倒的方法感到有点恼火,我完全不理解它.

我该如何回归这个价值?

Mar*_*nes 30

您可能最好坚持异常,但使用HttpResponseException也将返回Http状态代码.

throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized));
Run Code Online (Sandbox Code Playgroud)

这里有个好问题.

PS

实施起来可能更简单/更清洁 ActionFilterAttribute

public class AccessActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var result = //code to see if they have permission returns either 0 or 1

        if (result==0) 
        {
            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized));
        }
        base.OnActionExecuting(actionContext);
    }
Run Code Online (Sandbox Code Playgroud)

}

  • 这违反了HTTP 1.1.它说[401错误](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html)必须提供一个"WWW-Authenticate"来表示可接受的方案.`ApiController.Unauthorized`有一个参数.幸运的是,这不是403 Forbidden的问题. (2认同)

小智 6

您可以设置状态代码,而不是抛出异常

public class ExecutionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var result = 0;//code to see if they have permission returns either 0 or 1

        if (result == 0)
        {
            actionContext.Response = new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.Unauthorized,
                Content = new StringContent("Unauthorized User")
            };
        }
        base.OnActionExecuting(actionContext);
    }
}
Run Code Online (Sandbox Code Playgroud)