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
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
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:
RequestDelegate.Invoke or InvokeAsync.Task.HttpContext.Reference
in .net core 3.1
IHostingEnvironmentwas replaced byIWebHostEnvironmenttry to change your code to following:and also update your startup.cs
your JsonExceptionMiddleware should be defined something like this:
please see the documentation