Search code examples
c#asp.net-coremicroservicesmiddleware

Modifying BadRequest Error Message in ASP.NET Core Microservice Application


I am working on a microservice application developed in C# ASP.NET Core targeting .NET 6.0 framework. During security checks on my application, the security team identified an issue regarding "Improper Error handling."

The recommendation from the security team is that the application should not expose any detailed error handling messages to users, as this could potentially reveal sensitive implementation details.

Currently, when a 400 response is encountered, the error message includes detailed internal information, such as stack traces and error codes, which should not be exposed to users. Here is an example of the error message:

{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "some guid",
"errors": {
    "$.Id": [
        "The JSON value could not be converted to System.Int64. Path: $.Id | 
          LineNumber: 0 | BytePositionInLine: 41."
        ]
        }
   }

What I Need: I need to modify the error message returned in the BadRequest response to a generic message such as "Some error occurred. Please contact the support team with log details."

What I Have Tried:

I attempted to configure the InvalidModelStateResponseFactory in the MVC services to create a custom BadRequest response. However, I encountered issues as the Errors property is not writable in the ValidationProblemDetails class.

services.AddMvc().ConfigureApiBehaviorOptions(options =>
            {
                options.InvalidModelStateResponseFactory = context =>
                {
                   var problems = new CustomBadRequest(context);

                    return new BadRequestObjectResult(problems);
                };
            });

 public class CustomBadRequest : ValidationProblemDetails
    {
        public CustomBadRequest(ActionContext context) : base(context.ModelState)
        {
            Detail = this.Detail;
            Instance = this.Instance;
            Status = 400;
            Title = this.Title;
            Type = this.Type;
            Errors = "Unexpected Error Occurs";
        }
    }

I also tried creating a middleware to modify the response, but encountered difficulties as the new message was appended to the existing error message, rather than replacing it. Additionally, I faced an error stating: "System.InvalidOperationException: 'The response headers cannot be modified because the response has already started.'"

await _next(context);
            if (context.Response.StatusCode == (int)HttpStatusCode.BadRequest)
            {
                byte[] newStringData = Encoding.UTF8.GetBytes("This is a new string message.");
                await context.Response.Body.WriteAsync(newStringData, 0, newStringData.Length);
            }

I have also tried with Attribute.

Seeking Solution: I would appreciate any guidance or suggestions on how to properly modify the BadRequest error message in ASP.NET Core microservices.

Thank you for your assistance.


Solution

  • First of all, you can make the error look more generalized by using Json options:

    builder.Services.AddControllers()
        .AddJsonOptions(o => o.AllowInputFormatterExceptionMessages = false);
    

    You can also use ActionFilter for more customized errors, see this SO answer.