Click here to Skip to main content
15,879,474 members
Articles / Web Development
Tip/Trick

ASP.NET WEB API Custom Authorize and Exception Handling Attributes

Rate me:
Please Sign up or sign in to vote.
4.33/5 (7 votes)
27 May 2012CPOL 113.8K   19   5
How to implement the custom authorization and exception handling attribute in the ASP.NET Web API.

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.

C#
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)
        {
            // get value from header
            string authenticationToken = Convert.ToString(
              actionContext.Request.Headers.GetValues("authenticationToken").FirstOrDefault());
            //authenticationTokenPersistant
            // it is saved in some data store
            // i will compare the authenticationToken sent by client with
            // authenticationToken persist in database against specific user, and act accordingly
            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:

C#
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;
        }
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) -
Pakistan Pakistan
i am working as a senior software developer.

aamirposwal.blogspot.com

Comments and Discussions

 
QuestionMessage Closed Pin
4-Apr-16 22:28
Member 124372934-Apr-16 22:28 
QuestionDealing with only Authentication Pin
Muhammad N@beel24-Feb-14 3:42
professionalMuhammad N@beel24-Feb-14 3:42 
QuestionWhere is this code placed in the solution? Pin
R. Ian Lee15-Oct-13 5:10
R. Ian Lee15-Oct-13 5:10 
AnswerRe: Where is this code placed in the solution? Pin
aamir sajjad15-Oct-13 6:02
aamir sajjad15-Oct-13 6:02 
QuestionQuestion Pin
Member 798658410-May-12 5:48
Member 798658410-May-12 5:48 
AnswerRe: Question Pin
aamir sajjad13-May-12 2:38
aamir sajjad13-May-12 2:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.