我正在使用asp.net WebAPI,我需要创建一个自定义的ActionFilter,快速检查以查看请求URI的用户是否应该能够实际获取数据。
@H_502_2@他们已被授权通过基本身份验证使用Web服务,并且角色已通过自定义角色提供程序进行验证。
@H_502_2@我需要做的最后一件事是检查他们是否有权利在URI中使用参数来查看他们要求的数据。
@H_502_2@这是我的代码:
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(); } }@H_502_2@目前我只是抛出一个不是我想要的错误,我宁愿返回System.Net.HttpStatusCode.Unauthorized,但我有点被我所压倒的方法,我完全不了解它。 @H_502_2@我该如何回报这个价值?
解决方法
你可能最好坚持一个例外,但使用HttpResponseException也将返回一个Http状态代码。
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized));@H_502_2@很好的问题here关于这个。 @H_502_2@附: @H_502_2@实现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); }@H_502_2@}