2012-06-25 90 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

是的,我在找。如果有东西我会在这里发布。 –