ASP.NET Web API从响应中删除HttpError

Prz*_*ita 6 asp.net response http-error asp.net-web-api

我正在使用Microsoft ASP.NET Web API构建RESTful服务.

我的问题涉及Web API在出现问题时返回给用户的HttpErrors(例如400 Bad Request或404 Not Found).

问题是,我不希望得到系列化HttpError响应内容,因为它有时会提供太多的信息,因此它违反了OWASP安全规则,例如:

请求:

http://localhost/Service/api/something/555555555555555555555555555555555555555555555555555555555555555555555
Run Code Online (Sandbox Code Playgroud)

作为回复,我当然得到400,但有以下内容信息:

{
 "$id": "1",
 "Message": "The request is invalid.",
 "MessageDetail": "The parameters dictionary contains a null entry for parameter 'id'  of non-nullable type 'System.Int32' for method 'MyNamespaceAndMethodHere(Int32)' in 'Service.Controllers.MyController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."
}
Run Code Online (Sandbox Code Playgroud)

这样的事情不仅表明我的WebService基于ASP.NET WebAPI技术(也不是那么糟糕),而且还提供了有关我的命名空间,方法名称,参数等的一些信息.

我试图在Global.asax中设置IncludeErrorDetailPolicy

GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Never;
Run Code Online (Sandbox Code Playgroud)

是的,这确实很好,现在结果不包含MessageDetail部分,但仍然,我根本不想得到这个HttpError.

我还构建了自定义DelegatingHandler,但它也影响了我自己在控制器中生成的400和404,我不想发生这种情况.

我的问题是:是否有任何方便的方法来摆脱响应内容中的序列化HttpError?所有我希望用户回复他的错误请求是响应代码.

Cyb*_*axs 2

使用自定义 IHttpActionInvoker 怎么样?基本上,您只需发送一个空的 HttpResponseMessage 即可。

这是一个非常基本的例子:

public class MyApiControllerActionInvoker : ApiControllerActionInvoker
{
    public override Task<HttpResponseMessage> InvokeActionAsync(HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken)
    {
        var result = base.InvokeActionAsync(actionContext, cancellationToken);

        if (result.Exception != null)
        {
            //Log critical error
            Debug.WriteLine("unhandled Exception ");

            return Task.Run<HttpResponseMessage>(() => new HttpResponseMessage(HttpStatusCode.InternalServerError));
        }
        else if (result.Result.StatusCode!= HttpStatusCode.OK)
        {
            //Log critical error
            Debug.WriteLine("invalid response status");

            return Task.Run<HttpResponseMessage>(() => new HttpResponseMessage(result.Result.StatusCode));
        }


        return result;
    }
}
Run Code Online (Sandbox Code Playgroud)

在 Global.asax 中

GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpActionInvoker), new MyApiControllerActionInvoker());
Run Code Online (Sandbox Code Playgroud)

您可以做的另一件与 Web Api 无关的重要事情是删除过多的 asp.net 和 IIS HTTP 标头。是一个很好的解释。