我有两种方法的控制器,具有以下签名:
public class TestController
{
[HttpGet]
public ActionResult TestMethod1()
{
//here code
return Json(1, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public ActionResult TestMethod2(long userId)
{
//here code
return Json("userId= " + userId, JsonRequestBehavior.AllowGet);
}
}
我想为此方法创建以下路由器:
对于第一种方法:
http://domain/test/
对于第二种方法:
http://domain/test?userId={userId_value}
我尝试使用以下路线:
1
context.MapRoute("route_with_value",
"test/{userId}",
new { controller = "test", action = "TestMethod2" });
context.MapRoute("route_no_value",
"test",
new { controller = "test", action = "TestMethod1" });
但这种方式对我不起作用
2
context.MapRoute("route_with_value",
"test?userId={userId}",
new { controller = "test", action = "TestMethod2" });
context.MapRoute("route_no_value",
"test",
new { controller = "test", action = "TestMethod1" });
但是我收到了错误:
路线网址不能以' /'或者'〜'字符,它不能包含'?'字符。
是否可以为我的网址创建地图路线?
答案 0 :(得分:-1)
内置路由方法不知道查询字符串值。要让他们知道,您需要构建自定义路由或约束。
在这种情况下,只需要在查询字符串键存在时运行第一个路由,就可以使用简单的约束。
public class QueryStringParameterConstraint : IRouteConstraint
{
private readonly string queryStringKeyName;
public QueryStringParameterConstraint(string queryStringKeyName)
{
if (string.IsNullOrEmpty(queryStringKeyName))
throw new ArgumentNullException("queryStringKeyName");
this.queryStringKeyName = queryStringKeyName;
}
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
if (routeDirection == RouteDirection.IncomingRequest)
{
return httpContext.Request.QueryString.AllKeys.Contains(this.queryStringKeyName, StringComparer.OrdinalIgnoreCase);
}
return true;
}
}
context.MapRoute(
name: "route_with_value",
url: "test",
defaults: new { controller = "test", action = "TestMethod2" },
constraints: new { _ = new QueryStringParameterConstraint("userId") }
);
context.MapRoute(
name: "route_no_value",
url: "test",
defaults: new { controller = "test", action = "TestMethod1" }
);