How to return custom message if Authorize fails in WebAPI

There are different ways to do this but one of the best way could be custom authorization attributes.You just need to inherit the AuthorizeAttribute and override HandleUnauthorizedRequest() method of it. public class CustomAuthorization : AuthorizeAttribute { protected override void HandleUnauthorizedRequest(HttpActionContext actionContext) { actionContext.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.Forbidden, Content = new StringContent(“You are … Read more

Get ActionName, ControllerName and AreaName and pass it in ActionFilter Attribute

You could fetch them from the RouteData: protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext) { var rd = httpContext.Request.RequestContext.RouteData; string currentAction = rd.GetRequiredString(“action”); string currentController = rd.GetRequiredString(“controller”); string currentArea = rd.Values[“area”] as string; … }

Handling session timeout in ajax calls

You could write a custom [Authorize] attribute which would return JSON instead of throwing a 401 exception in case of unauthorized access which would allow client scripts to handle the scenario gracefully: [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class MyAuthorizeAttribute : AuthorizeAttribute { protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { if (filterContext.HttpContext.Request.IsAjaxRequest()) { filterContext.Result = new JsonResult { … Read more