How to serialize all exceptions to JSON in ASP.NET Core 3.1

45 views Asked by At

This is how I did in ASP.NET Core 2.1

var jsonExceptionMiddleware = new JsonExceptionMiddleware(
     app.ApplicationServices.GetRequiredService<IHostingEnvironment>());

Any assistance will be much appreciated. Thanks in advance

2

There are 2 answers

2
jakub podhaisky On

in .net core 3.1 IHostingEnvironment was replaced by IWebHostEnvironment try to change your code to following:

var jsonExceptionMiddleware = new JsonExceptionMiddleware(
    app.ApplicationServices.GetRequiredService<IWebHostEnvironment>());

and also update your startup.cs

public void ConfigureServices(IServiceCollection services)
{
    // Add services to the container.
    services.AddControllersWithViews();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
         
        app.UseMiddleware<JsonExceptionMiddleware>();
        
        app.UseHsts();
    }

    // Other middleware registrations...
}

your JsonExceptionMiddleware should be defined something like this:

public class JsonExceptionMiddleware
{
    private readonly RequestDelegate _next;
    private readonly IWebHostEnvironment _env;

    public JsonExceptionMiddleware(RequestDelegate next, IWebHostEnvironment env)
    {
        _next = next;
        _env = env;
    }

    // Middleware logic here...
}

please see the documentation

0
woodykiddy On

Firstly, create a custom middleware that catches exceptions and serializes them to JSON.

public class MyJsonExceptionMiddleware
{
    private readonly RequestDelegate _next;

    public MyJsonExceptionMiddleware(RequestDelegate next)
    {
         _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception ex)
        {
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            context.Response.ContentType = "application/json";

            var errorResponse = new
            {
                Error = ex.Message,
                StackTrace = ex.StackTrace
            };

            var json = JsonSerializer.Serialize(errorResponse);
            await context.Response.WriteAsync(json);
        }
    }
}

And then register this middleware MyJsonExceptionMiddleware at Startup.cs

app.UseMiddleware<MyJsonExceptionMiddleware>();

Things to note that the middleware class must include:

  • A public constructor with a parameter of type RequestDelegate.
  • A public method named Invoke or InvokeAsync.
  • This method must:
    • Return a Task.
    • Accept a first parameter of type HttpContext.

Reference

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/write?view=aspnetcore-3.1#middleware-class-1