Search code examples
c#asp.net.netasp.net-web-apiodata

How to remove the OData innererror from production services


The spec for Error Response says:

The value for the innererror name/value pair MUST be an object. The contents of this object are service-defined. Usually this object contains information that will help debug the service. The innererror name/value pair SHOULD only be used in development environments in order to guard against potential security concerns around information disclosure.

The spec is right, in asp.net the innererror property gives a useful info such as the stacktrace, but I really don't want to share this info with my API clients

As of yet, I haven't found a way of removing this property from the response, is it even possible?


Solution

  • Yes, it is possible, but is quite cumbersome.

    You need to do four things:

    Firstly, you should derive your own OData error serializer from the default implementation. The difference from the default ODataErrorSerializer will be to override the method containing the following code:

    bool includeDebugInformation = oDataError.InnerError != null;
    

    Change it to

    bool includeDebugInformation = oDataError.InnerError == null;
    

    or simply setting the value to false in your overridden implementation. Let's say your own OData error serializer is called MyODataErrorSerializer.

    Then you need to derive your own OData serializer provider from the default one. The difference from the DefaultODataSerializerProvider will be to change the following code:

    private static readonly ODataErrorSerializer _errorSerializer = new ODataErrorSerializer();
    

    to your own error serializer:

    private static readonly ODataErrorSerializer _errorSerializer = new MyODataErrorSerializer();
    

    Let's say your own serializer provider is called MyODataSerializerProvider.

    After that, do the similar thing to ODataMediaTypeFormatters. Derive a MyODataMediaTypeFormatters from DefaultODataMediaTypeFormatters which uses MyODataSerializerProvider instead of DefaultODataSerializerProvider.

    Finally, add the following code to your Web API OData implementation:

    config.Formatters.InsertRange(0, ODataMediaTypeFormatters.Create());