You can redirect to some other action :
public ActionResult EnterRevenue
{
if (!SecurityUtility.HasPermission(permission))
{
return View("Unauthorized", "Error");
}
return RedirectToAction("NotAuthorized","Error");
}
Assume we have ErrorController
with action NotAuthorized
which returns normal View which displays you are not authorized to view this page.
If you need this check on every action, then you need to implement custom action filter attribute in which you will have to check if it is normal request redirect else return staus as json and redirect from client side. See asp.net mvc check if user is authorized before accessing page
Here is a chunk of code:
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 on action like this:
[Authorization]
public ActionResult EnterRevenue
{
return this.PartialView("_EnterRevenue");
}