用角色注册路线 [英] register route with character
问题描述
我有2种方法的控制器,具有以下签名:
I have controller with 2 methods, with following signature:
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);
}
}
我想为此方法创建以下路由器:
I want to create the following routers for this methods:
-
对于第一种方法:
For the first method:
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" });
但是这种方式对我不起作用
but this way does not work for me
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" });
但是我得到了错误:
路由URL不能以'/'或'〜'字符开头,并且不能包含'?'字符.
The route URL cannot start with a '/' or '~' character and it cannot contain a '?' character.
是否可以为我的网址创建地图路线?
Is it possible to create map route for my urls?
推荐答案
内置路由方法不了解查询字符串值.为了让他们知道,您需要构建自定义路线或约束.
The built-in routing methods are unaware of query string values. To make them aware, you need to build custom routes or constraints.
在这种情况下,进行简单的约束将是可行的,因为只要存在查询字符串键就只想运行第一个路由即可.
In this case, making a simple constraint will work since you just want to run the first route whenever the query string key is present.
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" }
);
这篇关于用角色注册路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!