Can periods be used in Asp.Net Web Api Routes?

后端 未结 5 376
说谎
说谎 2020-12-03 05:15

I\'m working on moving an API project from raw http handlers where I\'m using periods in the paths:

http://server/collection/id.format

I wo

5条回答
  •  一生所求
    2020-12-03 06:08

    I'm accepting Darin's answer (yes, periods can be used in route urls) because it was specifically correct to my example, yet unhelpful to me. This is my fault for not specifically indicating that "id" is a string, not an integer.

    To use a period following a string parameter the routing engine needs hints in the form of a constraint:

    var c = new HttpSelfHostConfiguration(b);
    c.Routes.MapHttpRoute(
        name: "DefaultApiRoute",
        routeTemplate: "{controller}/{id}.{format}",
        defaults: new { id = RouteParameter.Optional, format = RouteParameter.Optional },
        constraints: new { id = "[^\\.]+" } // anything but a period
    );
    

    Adding the constraint to the preceding token allows inbound URLs to be correctly decomposed and processed. Without the hint, the "id" token can be interpreted to match the remaining extent of the URL. This is just a specific case of needing constraints to delineate boundaries between string parameters in general.

    Yes, periods can be used in URL routes in the Asp.Net Web API, but if they are to follow a string parameter be sure to apply the correct constraint to the route.

提交回复
热议问题