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
427 views
in Technique[技术] by (71.8m points)

c# - WebAPI route 404's when there is a trailing space in the URL

With the default web api route

config.Routes.MapHttpRoute(
            name: "API Default",
            routeTemplate: "api/{controller}/{id}",
            defaults: new
                      {
                          id = RouteParameter.Optional
                      }
            );

and a controller

public class TestController : ApiController
{
    [HttpGet]
    public HttpResponseMessage Get(string id)
    {
        return Request.CreateResponse(HttpStatusCode.OK, id);
    }
}

A request to 'api/test/1'

returns 1

If for some reason you send a request to 'api/test/1%20'

the route 404's.

Now this example may seem silly since browsers trim trailing spaces, but

for a route like 'api/{controller}/{id}/{extrastuff}'

the space in '1 ' would convert to '1%20' and the request will 404 on the route not being found.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Your issue has nothing to do with WebAPI itself but how Asp.Net handles some specific urls. And Asp.Net handles these urls in a very paranoid way, so you need to tell it to relax.

Add this line to your web.config under system.web:

<httpRuntime relaxedUrlToFileSystemMapping="true" />

You can read more about this topic:

Also on SO:


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

...