2012-02-18 126 views
1

我有检查认证和认证时使用的WebAPI返回错误的状态代码

throw new WebFaultException(HttpStatusCode.Unauthorized); 

但是这仍然会返回一个404 Not Found状态码到客户端/测试客户端失败,抛出异常的操作处理。

这是我的操作处理

public class AuthOperationHandler : HttpOperationHandler<HttpRequestMessage, HttpRequestMessage> 
{ 
    RequireAuthorizationAttribute _authorizeAttribute; 

    public AuthOperationHandler(RequireAuthorizationAttribute authorizeAttribute) : base("response") 
    { 
     _authorizeAttribute = authorizeAttribute; 
    } 

    protected override HttpRequestMessage OnHandle(HttpRequestMessage input) 
    { 
     IPrincipal user = Thread.CurrentPrincipal; 

     if (!user.Identity.IsAuthenticated) 
      throw new WebFaultException(HttpStatusCode.Unauthorized); 

     if (_authorizeAttribute.Roles == null) 
      return input; 

     var roles = _authorizeAttribute.Roles.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries); 

     if (roles.Any(role => user.IsInRole(role))) 
      return input; 

     throw new WebFaultException(HttpStatusCode.Unauthorized); 
    } 
} 

难道我做错了什么?

回答

1

我对你有好消息和坏消息。您正在使用的框架已演变为ASP.NET Web API。不幸的是,OperationHandlers不再存在。他们最接近的是ActionFilters。尽管如此,WCF Web API从不支持抛出WebFaultException,这是WCF SOAP遗留的遗迹。我认为这个异常被称为HttpWebException,然而,我从来没有使用它,我只是在响应中设置状态码。

+0

这并不好,我打算将我的api(基于预览版6)迁移到明天的测试版。我有一个基于操作处理程序的验证处理程序:( – 2012-02-20 19:48:52

+0

@AntonyScott ActionFilters能够完成大部分可以用OperationHandlers做的事情。 – 2012-02-20 20:39:39

+0

嗯,好吧,看起来我明天有一点改写:) – 2012-02-20 21:01:36