Introduction
Designing a robust error handling mechanism and returning meaningful error responses to clients is crucial for enhancing the reliability and user experience of your ASP.NET Core Web API. Here's a concise guide on how to achieve this using custom middleware.
Step 1. Create a new ASP.NET Core Web API project
Create the Asp.net core Web API Project using Visual Studio or CLI Command.
Step 2. Implement custom error-handling middleware
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Net;
using System.Threading.Tasks;
Author: Sardar Mudassar Ali Khan
public class ErrorHandlingMiddleware
{
private readonly RequestDelegate _next;
public ErrorHandlingMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private static Task HandleExceptionAsync(HttpContext context, Exception exception)
{
var statusCode = HttpStatusCode.InternalServerError;
var message = "An error occurred while processing your request.";
if (exception is ApplicationException)
{
statusCode = HttpStatusCode.BadRequest;
message = exception.Message;
}
var response = new { error = message };
var payload = JsonConvert.SerializeObject(response);
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)statusCode;
return context.Response.WriteAsync(payload);
}
}
Step 3. Configure the custom error-handling middleware
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
Author: Sardar Mudassar Ali Khan
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
// Add error handling middleware
services.AddTransient<ErrorHandlingMiddleware>();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
// Use the custom error handling middleware
app.UseMiddleware<ErrorHandlingMiddleware>();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
Join the conversation! Your thoughts help the community grow.