So my Q is as following (MVC 5): I got several types of default pages i'd like to start when my app is getting up.
1- for anonymous user
2...5 - for the other user roles which are automatically logged (cookie).
So that's pretty much a simple "if", i know, but meanwhile i was using the User.IsInRole("RoleName") method which cannot be used in RouteConfig.cs.
If it's a simple add of a Using statement, i apologize for the simplicity of the question in advance.
Update: I've managed to do it via some:
if(User.UserInRole("RoleName") return RedirectToAction("ActionName") in my default ActionResault.
Although it's not an elegant solution, nor it defines numerous default pages, but it makes the job done.
It's not as simple as you're thinking it is.
There are several scenarios you have to think about when doing this kind of thing. For example...
Scenario A:
Scenario B:
Scenario C:
I'm in a bit of a hurry, so it's probably hard to understand what I'm talking about. The point is, you have to think about the different ways a user might access your site. Typically, I wire this kind of functionality into the registration and login process. You won't be able to do what you want with routing.
One way to resolve this is to create a "Base" controller from which all your other controllers inherit. In this controller you could write your IF/CASE statements and you could override the base controller's Initialize, OnActionExecuting and OnResultExecuting methods to redirect where you want your user to end up based on your logic.
So basically you would create a base controller like this:
public class BaseController : Controller
{
protected string RedirectPath = string.Empty;
protected bool DoRedirect = false;
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
// Your logic to determine whether to redirect or not goes here. Bellow is an example...
if (requestContext.HttpContext.User.IsInRole("RoleName"))
{
DoRedirect = true;
RedirectPath = Url.Action("SomeAction", "SomeController");
}
}
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
if (DoRedirect)
{
// Option 1: TRANSFER the request to another url
filterContext.Result = new TransferResult(RedirectPath);
// Option 2: REDIRECT the request to another url
filterContext.Result = new RedirectResult(RedirectPath);
}
}
}
And then each one of your controller which has to adhere to this user role redirect logic needs to inherit from the BaseController:
public class HomeController : BaseController
{
// Controller logic here...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With