Sunday, January 22, 2017

Display message when user is not authorized in mvc

In this post I will show how to Display Error message when user is not Authorized, Continuing the previous POST i.e.,
Customizing Authorize attribute or Role based Authentication or Authorization in MVC

Previously I had shown how to....
DataTables in MVC:
OutPut:

AngularJS:
Replace CustomAuthorize method from previous post with the below code
  

public class CustomAuthorize : AuthorizeAttribute
{
 private string RedirectReason = "RedirectReason";

 public string Message { get; set; }

 protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
 {
  if (!filterContext.HttpContext.Request.IsAuthenticated)
  {
   base.HandleUnauthorizedRequest(filterContext);
  }
  else
  {
   if (!filterContext.Controller.TempData.ContainsKey(RedirectReason))
    filterContext.Controller.TempData.Add(RedirectReason, Message);
   else
    filterContext.Controller.TempData[RedirectReason] = Message;

   filterContext.Result = new RedirectToRouteResult(new
   RouteValueDictionary(new { controller = "Home", action = "Index" }));
  }
 }
}


And now Add message in CustomAuthorize Attribute for Action Result as shown below.
  

[CustomAuthorize(Roles = "Admin", Message = "You do not have permission.")]
public ActionResult Index()
{
    return View();
}

No comments:

Post a Comment