asp.net-mvc-4 – 返回状态代码未经授权在WebAPI中定制IActionFilter

我正在使用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,但我有点被我所压倒的方法,我完全不了解它。

我该如何回报这个价值?

解决方法

你可能最好坚持一个例外,但使用HttpResponseException也将返回一个Http状态代码
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);
    }

}

相关文章

这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...
最近用到了CalendarExtender,结果不知道为什么发生了错位,...
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence cha...