register route with character

瘦欲@ 提交于 2019-12-25 07:30:13

问题


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:

  1. For the first method:

    http://domain/test/

  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!