Reputation: 87
I am working with website with MVC4. Basic my web struct:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "ADMIN", action = "Index", id = UrlParameter.Optional }
);
But we have one page need to access with URL as: ABC.com/vairable. How to config. I config as below: but need to open with URL: ABC.com/Make/vairable:
routes.MapRoute(
"New",
"Make/{PROMOTION_NAME}",
new { controller = "Redeem", action = "MakeRedeem", PROMOTION_NAME = UrlParameter.Optional },
null,
new[] {"Project.Web.Controllers"});
Upvotes: 0
Views: 107
Reputation: 14741
You need make a custom constraint to your role. And add your role before default role. Custom constraint prevents match all URLs user typed and filter irrelevant URL's so other roles could match them. Consider this:
public class MyCatConstraint : IRouteConstraint
{
// suppose this is your promotions list. In the real world a DB provider
private string[] _myPromotions= new[] { "pro1", "pro2", "pro3" };
public bool Match(HttpContextBase httpContext, Route route,
string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
// return true if you found a match on your pros' list otherwise false
// In real world you could query from DB
// to match pros instead of searching from the array.
if(values.ContainsKey(parameterName))
{
return _myPromotions.Any(c => c == values[parameterName].ToString());
}
return false;
}
}
now add a role before default role with MyConstraint
:
routes.MapRoute(
name: "promotions",
url: "{PROMOTION_NAME}",
defaults: new { controller = "Redeem", action = "MakeRedeem" },
constraints: new { PROMOTION_NAME= new MyCatConstraint() },
namespaces: new[] {"Project.Web.Controllers"}
);
// your other roles here
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "ADMIN", action = "Index", id = UrlParameter.Optional }
);
Now URL example.com/pro1
maps to Redeem.MakeRedeem
action method but example.com/admin
maps to Admin.Index
Upvotes: 1
Reputation: 56909
We have one page need to access with URL as: ABC.com/vairable
There are basically 3 options, but I cannot give examples because you did not include any information as to what is expected to go in the "variable".
RouteBase
subclass. See this example.Upvotes: 1