You can redirect to another action:
public ActionResult EnterRevenue { if (!SecurityUtility.HasPermission(permission)) { return View("Unauthorized", "Error"); } return RedirectToAction("NotAuthorized","Error"); }
Suppose we have an ErrorController with a NotAuthorized action that returns a normal view, which indicates that you do not have permission to view this page.
If you need this check for each action, you need to implement a user action filter attribute, in which you will need to check if this is a normal redirect for an else request, return staus as json and redirect from the client side. See asp.net mvc to check if the user is allowed before accessing the page
Here is the code snippet:
public class AuthorizationAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { string actionName = filterContext.ActionDescriptor.ActionName; string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName; if (filterContext != null) { HttpSessionStateBase objHttpSessionStateBase = filterContext.HttpContext.Session; var userSession = objHttpSessionStateBase["userId"]; if (((userSession == null) && (!objHttpSessionStateBase.IsNewSession)) || (objHttpSessionStateBase.IsNewSession)) { objHttpSessionStateBase.RemoveAll(); objHttpSessionStateBase.Clear(); objHttpSessionStateBase.Abandon(); if (filterContext.HttpContext.Request.IsAjaxRequest()) { filterContext.HttpContext.Response.StatusCode = 403; filterContext.Result = new JsonResult { Data = "LogOut" }; } else { filterContext.Result = new RedirectResult("~/Home/Index"); } } else { if (!CheckAccessRight(actionName, controllerName)) { string redirectUrl = string.Format("?returnUrl={0}", filterContext.HttpContext.Request.Url.PathAndQuery); filterContext.HttpContext.Response.Redirect(FormsAuthentication.LoginUrl + redirectUrl, true); } else { base.OnActionExecuting(filterContext); } } } } }
and use it for action as follows:
[Authorization] public ActionResult EnterRevenue { return this.PartialView("_EnterRevenue"); }
source share