在网页API返回的状态代码未授权的自定义操作过滤器

问题描述 投票:21回答:2

我用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();
        }
    } 

目前,我只是抛出一个错误,这不是我想要的,我宁愿回到System.Net.HttpStatusCode.Unauthorized什么,但我对我重写方法有点恼火,我真的不完全理解它。

我怎么会去有关返回值?

asp.net-mvc-4 asp.net-web-api action-filter
2个回答
30
投票

你可能最好坚持一个例外,但使用它会返回一个HTTP状态代码太HttpResponseException。

throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized));

问得好here这一点。

附:

这可能是简单/清洁剂实现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);
    }

}


3
投票

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

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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.