I have a project with 2 areas /Admin and /User.
Admin's default route is /Admin/Home/Index and user's default route is /User/Home/Index.
Is it possible to implement routing to make their home URL to look like /Profile/Index but to show content from /Admin/Home/Index for admins and /User/Home/Index for users?
upd
Finally find out how to do it
context.MapRoute(
"Admin",
"Profile/{action}",
new { area = AreaName, controller = "Home", action = "Index" },
new { RoleConstraint = new Core.RoleConstraint() },
new[] { "MvcApplication1.Areas.Admin.Controllers" }
);
...
context.MapRoute(
"User",
"Profile/{action}",
new { area = AreaName, controller = "Home", action = "Index" },
new { RoleConstraint = new Core.RoleConstraint() },
new[] { "MvcApplication1.Areas.User.Controllers" }
);
public class RoleConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
string roleName = db.GetRoleByUserName(httpContext.User.Identity.Name);
string areaName = route.Defaults["area"].ToString();
return areaName == roleName;
}
}
It works, but as for me it's not the MVC way. Does anybody knows how to do it right?
What is Role Based Authentication In ASP.NET MVC? Role Based Authentication is Membership and Role providers. These providers allows us to define Roles, Users and assign roles to users which helps us to manage Authorization.
The three segments of a default route contain the Controller, Action and Id.
Yes. The example you showed is very close to many of the Microsoft provided samples for using Route Constraints. The routing engine acts as a pre-proxy (or router if you will) before the request is passed into a control. Items like IRouteConstraint are defined so you can do just what you described.
I like that solution as it's noted, but one thing to keep in mind is that routing itself shouldn't be used as the sole form of security. Just keep in mind that you should be securing your Controllers and Actions with the [Authorize] attribute, or however you're limiting access.
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