public class QueryStringConstraint : IRouteConstraint
{
public QueryStringConstraint(string value, bool ignoreCase = true)
{
Value = value;
IgnoreCase = ignoreCase;
}
public string Value { get; private set; }
public bool IgnoreCase { get; private set; }
public virtual bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
var currentValue = httpContext.Request.QueryString[parameterName];
return IgnoreCase ? currentValue.ToLowerInvariant() == Value.ToLowerInvariant() : currentValue == Value;
}
}
routes.MapRoute("Create page details", "Product/Create",
new { controller = "Product", action = "CreateDetails" },
new { page = new QueryStringConstraint("details") });
另外,如果你有這些行爲不同的車型,你可以做這樣的事情(與標準 「{控制器}/{行動}/{可選id}」 路線):
public class RequireRequestValueAttribute : ActionMethodSelectorAttribute
{
public RequireRequestValueAttribute(string name, string value = null, bool ignoreCase = true)
{
Name = name;
Value = value;
IgnoreCase = ignoreCase;
}
public string Name { get; private set; }
public string Value { get; private set; }
public bool IgnoreCase { get; private set; }
public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
{
var value = controllerContext.HttpContext.Request[Name];
return value != null && (Value == null || (IgnoreCase ? Value.ToLowerInvariant() == value.ToLowerInvariant() : Value == value));
}
}
[RequireRequestValue("Page", "Detail")]
public ActionResult Create(ProductDetailModel model)
{
return View(model);
}
[RequireRequestValue("Page", "Overview")]
public ActionResult Create(ProductOverviewModel model)
{
return View(model);
}