REST webapi URI GET with string instead of id not routing as expected

前端 未结 1 1402
鱼传尺愫
鱼传尺愫 2021-01-13 10:46

I have the following example where the request is http://{domain}/api/foo/{username} but I get a 404 status code back. No other Get actions exist on this contro

相关标签:
1条回答
  • 2021-01-13 11:30

    By default your route will look something like this:

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

    When you visit the url http://{domain}/api/foo/{username} the controller is mapped as foo and the optional id parameter is mapped to {username}. As you don't have a Get action method with a parameter called id a 404 is returned.

    To fix this you can either call the API method by changing the URL to be explicit about the parameter name:

    http://{domain}/api/foo?username={username}
    

    Or you could change your parameter name in your action method:

    public Foo Get(string id)
    {
        var foo = _service.Get<Foo>(username);
        return foo;
    }
    

    Or you could change your route to accept a username:

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{username}",
        defaults: new { username = RouteParameter.Optional }
    );
    
    0 讨论(0)
提交回复
热议问题