Web API and MVC with C# offer stellar global filters that can be registered in the App_Start/FilterConfig.cs file. For Web API and MVC the global filters goes inside the RegisterGlobalFilters function. This function contains an override based on whether you are applying the filter to MVC or Web API. Today we are going to look at how to implement an extension filter of the ExceptionFilterAttribute.
Exceptions inside your code typically occur in the following scenarios:
I think it is a code idea to handle this somewhere to return a proper error code to the user with a user-friendly friendly. Also a good opportunity to obscure sensitive data like a database error with details about your database tables.
Enter the ExceptionFilterAttribute
To get start I am going to create a file called OnExceptionAttribute. I place this file inside the App_Start folder. Here is a stubbed out file that will be filled in shortly.
The class OnExceptionAttribute extends the built-in ExceptionFilterAttribute class. The next part is I create a function called OnException that overrides the main function in the ExceptionFilterAttribute. This will be expanded shortly.
Before this code will be executed I know to update the previously file App_Start/FilterConfig.cs. The new filter will be added to the HttpFilterCollection. Here is an updated file:
Now when any exception occurs in our Web API our OnExceptionAttribute will be executed.
Let's now expand the OnExceptionAttribute function OnException to start handling a few exceptions and returning friendly HTTP Status Codes and response messages.
There is a lot of code in the above example, but here are the key things happening:
In my example a return a mix of HttpStatusCode to help developers how to handle a different response status code. I like to use the following statements to help you define what status code to send back:
That's it. Published on Apr 19, 2019 Tags: Uncategorized
| ASP.NET MVC and Web API Tutorial
| web api
| exceptionattributefilter
Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article
that you just finished reading.
No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner
or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in
and improve your skillset with any of the tutorials below.
Understanding what it means handling exceptions
Creating the OnExceptionAttribute extending the ExceptionFilterAttribue
using System.ComponentModel.DataAnnotations;
using System.Net;
using System.Net.Http;
using System.Web.Http.Filters;
namespace Api
{
public class OnExceptionAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
}
}
}
using System;
using System.Configuration;
using System.Web.Mvc;
namespace Api
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
}
///
using System.ComponentModel.DataAnnotations;
using System.Net;
using System.Net.Http;
using System.Web.Http.Filters;
namespace Api
{
public class OnExceptionAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
var exceptionType = context.Exception.GetType().ToString();
var exception = context.Exception.InnerException ?? context.Exception;
HttpResponseMessage httpResponseMessage;
switch (exceptionType)
{
case "System.Data.DuplicateNameException":
httpResponseMessage = CreateHttpResponseMessage(context.Request,
HttpStatusCode.BadRequest, context.Exception);
break;
case "System.Data.ObjectNotFoundException":
case "System.Data.Entity.Core.ObjectNotFoundException":
httpResponseMessage = CreateHttpResponseMessage(context.Request,
HttpStatusCode.NotFound, context.Exception);
break;
case "System.UnauthorizedAccessException":
httpResponseMessage = CreateHttpResponseMessage(context.Request,
HttpStatusCode.Forbidden, context.Exception);
break;
case "System.ComponentModel.DataAnnotations.ValidationException":
httpResponseMessage = CreateHttpResponseMessage(context.Request,
HttpStatusCode.BadRequest, context.Exception as ValidationException);
break;
case "System.Data.Entity.Infrastructure.DbUpdateException":
httpResponseMessage = CreateHttpResponseMessage(context.Request,
HttpStatusCode.InternalServerError, "An error occurred, please try again.");
break;
case "System.Data.Entity.Core.OptimisticConcurrencyException":
case "System.Data.OptimisticConcurrencyException":
httpResponseMessage = CreateHttpResponseMessage(context.Request,
HttpStatusCode.InternalServerError, "An error occurred, please try again. If error persists contact support.");
break;
default:
httpResponseMessage = CreateHttpResponseMessage(context.Request,
HttpStatusCode.InternalServerError, context.Exception);
break;
}
context.Response = httpResponseMessage;
}
public HttpResponseMessage CreateHttpResponseMessage(HttpRequestMessage request, HttpStatusCode statusCode, string error)
{
return request.CreateResponse(statusCode, error);
}
}
}
Related Posts
Tutorials
Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.