How to configure ASP.NET Core to return exceptions in camel case?

Viewed 362

When my application throws an unhandled exception, I return a status code 500 (internal server error), as in this example:

[HttpGet]
public ActionResult<string> Get()
{
    try
    {
        throw new Exception("Exception return test.");
    }
    catch (Exception ex)
    {
        return StatusCode(StatusCodes.Status500InternalServerError, ex);
    }
}

The JSON return is:

{
  "ClassName": "System.Exception",
  "Message": "Exception return test.",
  "Data": null,
  "InnerException": null,
  "HelpURL": null,
  "StackTraceString": null,
  "RemoteStackTraceString": null,
  "RemoteStackIndex": 0,
  "ExceptionMethod": null,
  "HResult": -2146233088,
  "Source": null,
  "WatsonBuckets": null
}

But I want all properties formatted in camel case.

In ASP.NET Web API you could implement a IContentNegotiator interface and replace it in your HttpConfiguration, like explained here. With this configuration, every output from the API is in camel case, including exception messages.

In ASP.NET Core 2.2, even though object properties return by the API are in camel case by default, exceptions aren't.

I tried (in Startup.cs):

services.AddMvc()
    .AddJsonOptions(options =>
    {
        options.SerializerSettings.ContractResolver =
            new CamelCasePropertyNamesContractResolver();
        options.UseCamelCasing(true);
    })

but no luck. I also inspected the OutputFormatters and confirmed that the JsonOutputFormatter already had CamelCasePropertyNamesContractResolver as its ContractResolver. I tried it anyway, but as expected, no change in the results:

services.AddMvc()
    .AddMvcOptions(options =>
    {
        foreach (var item in options.OutputFormatters)
        {
            if (item is JsonOutputFormatter a)
            {
                // This was pointless
                a.PublicSerializerSettings.ContractResolver 
                    = new CamelCasePropertyNamesContractResolver();
            }
        }
    })
0 Answers
Related