Introduction
In this article, I will explain and demonstrate how to implement the custom authorization and exception handling attribute in the ASP.NET Web API.
Custom Authorize Attribute
in ASP.NET WEB API you can extend "AuthorizeAttribute
" to implement custom authorization filter to control the access to the application.
I have overridden the "OnAuthorization
" method to check custom authorization rules. In this implementation, I am assuming that user
will send and receive the data through "HTTP headers".
Following is code example how to implement it.
public class CustomAuthorize : System.Web.Http.AuthorizeAttribute
{
public override void OnAuthorization(
System.Web.Http.Controllers.HttpActionContext actionContext)
{
base.OnAuthorization(actionContext);
if (actionContext.Request.Headers.GetValues("authenticationToken") != null)
{
string authenticationToken = Convert.ToString(
actionContext.Request.Headers.GetValues("authenticationToken").FirstOrDefault());
if (authenticationTokenPersistant != authenticationToken)
{
HttpContext.Current.Response.AddHeader("authenticationToken", authenticationToken);
HttpContext.Current.Response.AddHeader("AuthenticationStatus", "NotAuthorized");
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden);
return;
}
HttpContext.Current.Response.AddHeader("authenticationToken", authenticationToken);
HttpContext.Current.Response.AddHeader("AuthenticationStatus", "Authorized");
return;
}
actionContext.Response =
actionContext.Request.CreateResponse(HttpStatusCode.ExpectationFailed);
actionContext.Response.ReasonPhrase = "Please provide valid inputs";
}
}
Custom Handle Exception attribute:
To implement custom Handle Exception attribute you need to extend "ExceptionFilterAttribute
", and override "OnException
" method.
You can find the example below:
public class HandleExceptionAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
if (actionExecutedContext.Exception != null)
{
var exception = actionExecutedContext.Exception;
var response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.InternalServerError;
response.ReasonPhrase = exception.Message;
actionExecutedContext.Result = response;
}
}
}