我正在使用MVC4的网站。 基本的我的web结构:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "ADMIN", action = "Index", id = UrlParameter.Optional }
);
但是我们有一个页面需要使用URL访问:ABC.com/vairable。 如何配置。 我配置如下:但需要打开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"});
答案 0 :(得分:1)
我们需要使用以下网址访问一个页面:ABC.com/vairable
基本上有3个选项,但我不能举例,因为你没有提供关于"变量"的预期内容的任何信息。
RouteBase
子类。见this example。答案 1 :(得分:1)
您需要为您的角色制定自定义约束。并在默认角色之前添加您的角色。自定义约束可防止匹配用户键入的所有URL并过滤不相关的URL,以便其他角色可以匹配它们。考虑一下:
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;
}
}
现在使用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 }
);
现在,网址example.com/pro1
映射到Redeem.MakeRedeem
操作方法,但example.com/admin
映射到Admin.Index