My MVC 3 webapp has different parts which require to check whether the user is a user or an admin, they all get access to the same pages, except some pages have controllers (buttons and textboxes) that only admins can see. I do that check by putting the user’s access level into my viewmodel and doing a check:
@if (Model.UserAccess != "Viewer")
{
[do something]
}
I check in my action what access the logged in user has. If the session were to timeout I redirect them to the logon page.
My action is called from a Project page view and loaded as a partial:
@{Html.RenderAction("CategoryList", "Home", new { categoryId = Model.CategoryId });}
And my Controller:
public PartialViewResult CategoryList(int categoryid = 0)
{
var useraccess = GetUseraccess();
[blablabla stuff done here]
var model = new CategoryViewModel()
{
CategoryList = categorylist
UserAccess = useraccess
};
return PartialView(model);
}
public string GetUseraccess()
{
var useraccess = "viewer"; //default
var check = SessionCheck();
if (check == "expired")
{
ModelState.AddModelError("", "Session expired. Please login again.");
Response.Redirect("/Account/LogOn");
}
else if (check == "admin")
{
useraccess = "admin";
}
return useraccess;
}
public string SessionCheck()
{
if (Session["UserAccess"] == null)
{
return "expired";
}
else if ((string)Session["UserAccess"] == "admin")
{
return "admin";
}
else // viewer
{
return "viewer";
}
}
Now that works fine. However I’ve been trying to implement a custom attribute that would check the session’s expiration before the controller is fired:
public class CheckUserAccessSessionAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var useraccess = filterContext.HttpContext.Session["UserAccess"];
if ((string)useraccess == null)
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Account", action = "LogOn" }));
}
}
}
[CheckUserAccessSession]
public PartialViewResult CategoryList(int categoryid = 0)
{
[same stuff as above here]
}
I get the error
Exception Details: System.InvalidOperationException: Child actions are not allowed to perform redirect actions.
I understand why the error happens. But I haven’t found how to go around it. Similarly I’d like to send to my action some data from another custom attribute but that also isn’t working because of the RedirectToRouteResult.
Your issue here that is you’re returning a PartialViewResult on that action method, and by definition the output of that action method is going to be only a portion of the full request served by IIS. You should be doing permissions checking on the action method that serves the full view in which the partial view is incorporated.
Technically when you’re calling Response.Redirect in your initial implementation you’re breaking far away from the ASP.NET MVC design conventions; even though it works, it’s bad design.