I have an application where I need to apply logic only badly formed requests before returning the response (status code:400).
To do so I have researched about error handling in ASP.NET Core, and based on this solution I tried the following:
public class ErrorHandlingMiddleware
{
private readonly RequestDelegate next;
public ErrorHandlingMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context /* other dependencies */)
{
try
{
await next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private static Task HandleExceptionAsync(HttpContext context, Exception exception)
{
if (context.Response.StatusCode == StatusCodes.Status400BadRequest)
{
//apply logic
}
var result = JsonConvert.SerializeObject(new { error = exception.Message });
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)StatusCodes.Status400BadRequest;
return context.Response.WriteAsync(result);
}
}
and in Startup:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMiddleware(typeof(ErrorHandlingMiddleware));
app.UseMvc();
}
Unfortunately the above solution did not work, when I debug I see that context.Response.StatusCode
is always 200 even if the request is badly formed.
What am I missing here? any insights would be appreciated.