Harry
Harry

Reputation: 3205

Web API URI version not working as expected

I am trying to use URI versioning, however I am a little confused as to why I receive the following error:

<Error>
<Message>
No HTTP resource was found that matches the request URI 'http://localhost:61496/api/v1/foo/create'.
</Message>
<MessageDetail>
No type was found that matches the controller named 'foo'.
</MessageDetail>
</Error>

Controller

 public class FooController : ApiController
{
    private readonly IFoo _ifoo;

    public FooController(IFoo foo)
    {
        _ifoo = foo;
    }

    /// <summary>
    /// Return an instance of a Foo object.
    /// </summary>
    /// <returns></returns>
    [Route("api/v1/[controller]/create")]
    [HttpGet]
    public Foo Create()
    {
        return _ifoo.Create();
    }

}

WebApiConfig

 public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

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

Update this work but why??

 [Route("api/v1/foo/create")]
    [HttpGet]
    public Foo Create()
    {
        return _ifoo.Create();
    }

Upvotes: 2

Views: 165

Answers (1)

Nkosi
Nkosi

Reputation: 247561

Based on the configuration shown, you are using and not

Token replacements like [controller] and [action] in route templates were only added to the more recent asp.net-core version.

For convenience, attribute routes support token replacement by enclosing a token in square-braces ([, ]). The tokens [action], [area], and [controller] are replaced with the values of the action name, area name, and controller name from the action where the route is defined

Reference Routing to controller actions in ASP.NET Core: Token replacement in route templates ([controller], [action], [area])

this is why [Route("api/v1/[controller]/create")] does not work when you try to browse to api/v1/foo/create as the former is taken as a literal string in the version of the framework that is being used.

Reference Attribute Routing in ASP.NET Web API 2

Upvotes: 2

Related Questions