2012-10-22 94 views
8

是否有改变的错误信息,如网络API的默认行为的一种方式:asp.net的Web API - 默认错误消息

GET /trips/abc 

会回应(转述):

HTTP 500 Bad Request 

{ 
    "Message": "The request is invalid.", 
    "MessageDetail": "The parameters dictionary contains a null entry for parameter 'tripId' of non-nullable type 'System.Guid' for method 'System.Net.Http.HttpResponseMessage GetTrip(System.Guid)' in 'Controllers.TripController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter." 
} 

我我想避免发布关于我的代码的这个相当详细的信息,取而代之的是类似于:

HTTP 500 Bad Request 
{ 
    error: true, 
    error_message: "invalid parameter" 
} 

我可以在UserController中执行此操作,但代码执行甚至没有达到那么远。

编辑:

我发现从输出除去详细的错误消息的一种方式,使用这行代码在Global.asax.cs中:

GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = 
IncludeErrorDetailPolicy.LocalOnly; 

这产生类似这样的消息:

{ 
    "Message": "The request is invalid." 
} 

这是更好的,但是不正是我想要的 - 我们已经指定了一些数字错误代码,它映射到详细的错误信息的客户端。我想只输出相应的错误代码(即我能之前输出选择,preferrably通过看发生什么样的例外),例如:

{ error: true, error_code: 51 } 

回答

7

你可能想保留的形状即使您想隐藏有关实际异常的详细信息,也会将该数据视为类型HttpError。要做到这一点,你可以添加一个自定义的DelegatingHandler来修改你的服务抛出的HttpError。

这里的DelegatingHandler如何可能看起来像一个示例:

public class CustomModifyingErrorMessageDelegatingHandler : DelegatingHandler 
{ 
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) 
    { 
     return base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>((responseToCompleteTask) => 
     { 
      HttpResponseMessage response = responseToCompleteTask.Result; 

      HttpError error = null; 
      if (response.TryGetContentValue<HttpError>(out error)) 
      { 
       error.Message = "Your Customized Error Message"; 
       // etc... 
      } 

      return response; 
     }); 
    } 
} 
+0

完美,谢谢! – doque

+3

如果你想知道在哪里添加它,可以通过调用'config.MessageHandlers.Add(new YourDelegatingHandler())'来添加它,通常在启动逻辑的'Register(HttpConfiguration config)'方法中。 –

+0

不应该在构建响应内容之后替换响应内容,我们是不是应该首先定制负责构建响应的类/服务? – dgaspar

2

张曼玉的回答为我工作为好。感谢发布!

只是想一些比特她代码进一步澄清:

HttpResponseMessage response = responseToCompleteTask.Result; 
HttpError error = null; 

if ((!response.IsSuccessStatusCode) && (response.TryGetContentValue(out error))) 
{ 
    // Build new custom from underlying HttpError object. 
    var errorResp = new MyErrorResponse(); 

    // Replace outgoing response's content with our custom response 
    // while keeping the requested MediaType [formatter]. 
    var content = (ObjectContent)response.Content; 
    response.Content = new ObjectContent(typeof (MyErrorResponse), errorResp, content.Formatter); 
} 

return response; 

其中:

public class MyErrorResponse 
    { 
     public MyErrorResponse() 
     { 
      Error = true; 
      Code = 0; 
     } 

     public bool Error { get; set; } 
     public int Code { get; set; } 
    }