问题
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/For the second method:
http://domain/test?userId={userId_value}
I tried to use the following routes:
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" });
but I get the error:
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?
回答1:
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;
}
}
Usage
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" }
);
来源:https://stackoverflow.com/questions/38160184/register-route-with-character