Reputation: 34188
i am not advance developer in MVC.
i just read a post from this url Defining conditional routes
the question was if user login as admin then he will be redirect to admin controller and if user login as normal user then he will be redirected as user controller.
this was things has been done but i just do not understand the code how it is working. so help me to understand the code.
using System;
using System.Web;
using System.Web.Routing;
namespace Examples.Extensions
{
public class MustBeAdmin : IRouteConstraint
{
public MustBeAdmin()
{ }
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
// return true if user is in Admin role
return httpContext.User.IsInRole("Admin");
}
}
}
routes.MapRoute(
"Admins", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Admin", action = "Index", id = UrlParameter.Optional }, // Parameter default
new { controller = new MustBeAdmin() } // our constraint
);
1) bool Match() is any in built method or is it user define one ?
2) already action and controller mention this way in route
new { controller = "Admin", action = "Index", id = UrlParameter.Optional }
but again mention the same like this way
new { controller = new MustBeAdmin() }
3) what is the meaning of this line { controller = new MustBeAdmin() } ?
nowhere it is specific that if user login as normal user then he will be redirected to user controller.
please help me to understand the code.
thanks
Upvotes: 1
Views: 3062
Reputation: 22416
You've got your logic flipped. Here’s how you can use the NotEqual constraint to exclude the /Admin pages from the Default route:
using System;
using System.Web;
using System.Web.Routing;
public class NotEqual : IRouteConstraint
{
private string _match = String.Empty;
public NotEqual(string match)
{
_match = match;
}
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
return !httpContext.User.IsInRole(_match);
}
}
routes.MapRoute(
"Admins", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Admin", action = "Index", id = UrlParameter.Optional }, // Parameter default
new { controller = new NotEqual("Admin") }
);
It's never going to match for a non-admin.
Match
is a method on the IRouteConstraint
interface:
Upvotes: 1