Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

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

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 would like to follow the same URL schema in a Web Api (self-hosted) version, and tried this:

var c = new HttpSelfHostConfiguration(b);
c.Routes.MapHttpRoute(
    name: "DefaultApiRoute",
    routeTemplate: "{controller}/{id}.{format}",
    defaults: new { id = RouteParameter.Optional, format = RouteParameter.Optional },
    constraints: null
);

Unfortunately, that doesn't seem to resolve (consistent 404's on /foo, /foo/bar and /foo/bar.txt). A similar pattern using a slash before 'format' works fine:

var c = new HttpSelfHostConfiguration(b);
c.Routes.MapHttpRoute(
    name: "DefaultApiRoute",
    routeTemplate: "{controller}/{id}/{format}",
    defaults: new { id = RouteParameter.Optional, format = RouteParameter.Optional },
    constraints: null
);

I haven't yet delved into the code for the Web Api, and before I do thought I'd ask here to see if this is a known, or perhaps even justified limitation in Web Api.

UPDATE: I neglected to mention that "id" and "format" are strings, which turns out to be important for the solution to this question. Adding a constraint to exclude periods from the "id" token solves the 404 problem.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I was able to achieve this by doing the following: replace "*." with "*" in system.webServer.handlers in web.config, i.e. remove the period.

<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...