ASP.NET MVC: Route with optional parameter, but if supplied, must match \d+

前端 未结 6 1306
孤街浪徒
孤街浪徒 2020-11-29 12:00

I\'m trying to write a route with a nullable int in it. It should be possible to go to both /profile/ but also /profile/\\d+.

route         


        
6条回答
  •  借酒劲吻你
    2020-11-29 12:32

    It's possible something changed since this question was answered but I was able to change this:

    routes.MapPageRoute(
        null,
        "projects/{operation}/{id}",
        "~/Projects/ProjectWizard.aspx",
        true,
        new RouteValueDictionary(new
        {
            operation = "new",
            id = UrlParameter.Optional
        }),
        new RouteValueDictionary(new
        {
            id = new NullableExpressionConstraint(@"\d+")
        })
    );
    

    With this:

    routes.MapPageRoute(
        null,
        "projects/{operation}/{id}",
        "~/Projects/ProjectWizard.aspx",
        true,
        new RouteValueDictionary(new
        {
            operation = "new",
            id = UrlParameter.Optional
        }),
        new RouteValueDictionary(new
        {
            id = @"\d*"
        })
    );
    

    Simply using the * instead of the + in the regular expression accomplished the same task. The route still fired if the parameter was not included, but if included it would only fire if the value was a valid integer. Otherwise it would fail.

提交回复
热议问题