2012-02-18 123 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