2013-04-16 75 views
1

我正在使用MVC 4 Web API框架編寫Web API。我正在使用BASIC身份驗證,並使用從DelegatingHandler繼承的自定義身份驗證消息處理程序。在身份驗證處理程序中設置響應錯誤

除了我的錯誤處理,一切都很好用。

我使用Web API作爲現有認證機制的包裝,並在用戶密碼過期時引發異常。在API的操作方法,我可以拋出一個HTTPResponseException輕鬆地處理這一點,我得到一個整潔的小JSON對象,如下圖所示:

{ 
"Message": "Password is expired." 
} 

如果我嘗試同樣的方法在我的驗證消息處理程序,我得到所有令人討厭的.NET響應輸出。

<html> 
<head> 
    <title>Processing of the HTTP request resulted in an exception. Please see the HTTP response returned by the 'Response' property of this exception for details.</title> 
    <style> 
    body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} 
    p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px} 
... you get the idea ... 

我想我已經接近...在SendAsync

catch (Exception ex) 
{ 
    var response = request.CreateErrorResponse(HttpStatusCode.Unauthorized, ex.Message); 
    response.Headers.Add("WWW-Authenticate", "Basic realm=\"myrealm\""); 
} 

這裏,也許如果我能以某種方式從我的響應對象中獲取Task<HttpResponseMessage>回來,我想我可能是好的。

基本上我的問題是「應該如何處理異常,以便我能夠向用戶返回一個不錯的json/xml對象?」

還有一點要注意,這是.NET 4,而不是4.5。我已經看到幾個使用await關鍵字的示例,但在這種情況下不起作用。

回答

2

你可以用在任務的迴應:

catch (Exception) 
{ 
    return Task<HttpResponseMessage>.Factory.StartNew(() => 
    { 
     var response = request.CreateErrorResponse(HttpStatusCode.Unauthorized, ex.Message); 
     response.Headers.Add("WWW-Authenticate", "Basic realm=\"myrealm\""); 
     return response; 
    }); 
} 

return base.SendAsync(request, cancellationToken); 
+0

輝煌,謝謝! – earthling

相關問題