asp.net的Web API - 默认错误信息 [英] asp.net Web Api - Default Error Messages

查看:262
本文介绍了asp.net的Web API - 默认错误信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有改变网页API的默认行为的错误消息,如操作的方法:

  GET /车次/ ABC

与回应(转述):

  HTTP 500错误的请求{
    消息:请求是无效的。
    MessageDetail:参数词典共包含参数无效项非可空类型的TRIPID'的System.Guid'的方法'System.Net.Http.Htt presponseMessage GetTrip(的System.Guid)'在' Controllers.TripController'。一个可选参数必须是引用类型,可空类型,或声明为可选参数。
}

我想避免给了我的code这个相当的相关详细信息,而是喜欢的东西替代它:

  HTTP 500错误的请求
{
    错误:真实,
    ERROR_MESSAGE:无效的参数
}

我能做到这一点是由于UserController内,但code执行甚至不走那么远。

编辑:

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

  GlobalConfiguration.Configuration.IncludeErrorDetailPolicy =
IncludeErrorDetailPolicy.LocalOnly;

这会产生类似这样的消息:

  {
    消息:请求是无效的。
}

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

  {错误:真实,错误_ code:51}


解决方案

您可能要保留的数据类型HTTPError这样即使你想隐瞒实际的异常的详细信息的形状。要做到这一点,你可以添加自定义DelegatingHandler修改HTTPError这样您的服务罚球。

下面是对DelegatingHandler如何可能看起来像一个示例:

 公共类CustomModifyingErrorMessageDelegatingHandler:DelegatingHandler
{
    保护覆盖任务< Htt的presponseMessage> SendAsync(HTT prequestMessage请求的CancellationToken的CancellationToken)
    {
        返回base.SendAsync(请求的CancellationToken).ContinueWith< Htt的presponseMessage>((responseToCompleteTask)=>
        {
            HTT presponseMessage响应= responseToCompleteTask.Result;            HTTPError这样的错误= NULL;
            如果(response.TryGetContentValue< HTTPError这样>(超时错误))
            {
                返回Error.message =您的自定义错误消息;
                //等等...
            }            返回响应;
        });
    }
}

Is there a way of changing Web Api's default behavior for error messages, such as:

GET /trips/abc

Responds with (paraphrased):

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."
}

I'd like to avoid giving out this rather detailled information about my code, and instead replace it with something like:

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

I'd be able to do this inside the UserController, but the code execution doesn't even go that far.

edit:

I've found a way of removing detailed error messages from the output, using this line of code in Global.asax.cs:

GlobalConfiguration.Configuration.IncludeErrorDetailPolicy =
IncludeErrorDetailPolicy.LocalOnly;

This produces a message like this:

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

which is better, however not exactly what I want - We've specified a number of numeric error codes, which are mapped to detailed error messages client-side. I would like to only output the appropriate error code (that I'm able to select prior to output, preferrably by seeing what kind of exception occured), for example:

{ error: true, error_code: 51 }

解决方案

You might want to keep the shape of the data as the type HttpError even if you want to hide detailed information about the actual exception. To do that, you can add a custom DelegatingHandler to modify the HttpError that your service throws.

Here is a sample of how the DelegatingHandler might look like:

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;
        });
    }
}

这篇关于asp.net的Web API - 默认错误信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆