2012-06-25 92 views
4

我ApiKey驗證的示例代碼如下(我使用MVC4網頁API RC)給出:如何從Catch塊返回錯誤消息。現在空返回

public class ApiKeyFilter : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(HttpActionContext context) 
    { 
     //read api key from query string 
     string querystring = context.Request.RequestUri.Query; 
     string apikey = HttpUtility.ParseQueryString(querystring).Get("apikey"); 

     //if no api key supplied, send out validation message 
     if (string.IsNullOrWhiteSpace(apikey)) 
     {     
      var response = context.Request.CreateResponse(HttpStatusCode.Unauthorized, new Error { Message = "You can't use the API without the key." }); 
      throw new HttpResponseException(response); 
     } 
     else 
     {   
      try 
      { 
       GetUser(decodedString); //error occurred here 
      } 
      catch (Exception) 
      { 
       var response = context.Request.CreateResponse(HttpStatusCode.Unauthorized, new Error { Message = "User with api key is not valid" }); 
       throw new HttpResponseException(response); 
      } 
     } 
    } 
} 

這裏的問題是與Catch塊聲明。我只是想自定義錯誤消息給用戶。但沒有發送。它顯示黑屏

但是,下面的語句是運作良好,並正確地發送了驗證錯誤消息:

if (string.IsNullOrWhiteSpace(apikey)) 
{     
    var response = context.Request.CreateResponse(HttpStatusCode.Unauthorized, new Error { Message = "You can't use the API without the key." }); 
    throw new HttpResponseException(response); 
} 

有什麼,我做錯了。

回答

12

我在完全相同的場景中遇到同樣的問題。但是,在這種情況下,您需要返回響應中的一些內容才能顯示,而不是真的拋出異常。因此,這種變化現在你正在返回你的迴應

catch (Exception) 
{ 
    var response = context.Request.CreateResponse(httpStatusCode.Unauthorized); 
    response.Content = new StringContent("User with api key is not valid"); 
    context.Response = response; 
} 

,與將顯示在地方空白屏幕的內容:因此,基於這一點,我想你的代碼更改爲以下。

+0

感謝Paige Cook,我現在可以獲取StringContent「帶api鍵的用戶無效」而不是空白屏幕:-)。但另一個關心的問題是,我不想使用純文本,而是想以當前格式化程序的格式(如xml或json)來獲取結果。爲此,我需要指定response.Content = new Error {Message =「如果沒有密鑰,則無法使用API​​。」 }。此代碼不起作用,並且是編譯錯誤。如何在這裏寫代碼行? –

+0

不幸的是,我不知道該怎麼做。有一種方法可以確定請求的MediaType並將消息格式化爲相同的MediaType。 –

+0

是的,我在找。如果有東西我會在這裏發佈。 –