SchwabenCode Blog Post

ASP.NET Core ModelState Validation Filter

I like my ASP.NET Core controllers and actions very clean and I recommend to not catch all Exceptions inside your Action.

You can have it much easier and simplier - with your custom Exception Middleware.

For exemaple I want to catch all NotImplementedException (I hope you do not have any of them in your final code) and return the HTTP status code 501 (HttpStatusCode.NotImplemented) I can just use this middleware implementation:

 1    public class NotImplementedExceptionMiddleware
 2    {
 3        private readonly RequestDelegate _next;
 4        private readonly ILogger<NotImplementedExceptionMiddleware> _logger;
 5
 6        public NotImplementedExceptionMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
 7        {
 8            _next = next ?? throw new ArgumentNullException(nameof(next));
 9            _logger = loggerFactory?.CreateLogger<NotImplementedExceptionMiddleware>() ?? throw new ArgumentNullException(nameof(loggerFactory));
10        }
11
12        public async Task Invoke(HttpContext context)
13        {
14            try
15            {
16                await _next(context);
17            }
18            catch (NotImplementedException ex)
19            {
20                if (!context.Response.HasStarted)
21                {
22                    int errorCode = (int)HttpStatusCode.NotImplemented;
23
24                    context.Response.Clear();
25                    context.Response.StatusCode = errorCode;
26                    context.Response.ContentType = "application/json";
27
28                    // this is a sample error result object
29                    ErrorResult error = new ErrorResult("Not implemented", ex.Message);
30                    await context.Response.WriteAsync(error.ToJson());
31                }
32            }
33        }
34    }
1A simple extention to register the middleware cleaner:
2
3    public static class NotImplementedExceptionMiddlewareExtensions
4    {
5        public static IApplicationBuilder UseNotImplementedExceptionMiddleware(this IApplicationBuilder builder)
6        {
7            return builder.UseMiddleware<NotImplementedExceptionMiddleware>();
8        }
9    }

And register this middleware:

 1    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
 2    public void Configure(IApplicationBuilder app, IHostingEnvironment env, IPingPongService pingPongService)
 3    {
 4        if (env.IsDevelopment())
 5        {
 6            app.UseDeveloperExceptionPage();
 7        }
 8
 9        // Use Middleware
10        app.UseNotImplementedExceptionMiddleware();
11
12        app.UseMvc(); 
13    }

Done.


Comments

Twitter Facebook LinkedIn WhatsApp