Reputation: 521
I've written a controller like below (.net core 2.1):
[ApiVersion("1")]
[Consumes("application/json")]
[Produces("application/json")]
[Route("v{version:apiVersion}/[controller]")]
public class AccountController : ControllerBase
{
// GET: api/Account
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
I'm calling the above controller in this way (swagger call):
curl -X GET "https://localhost:44363/v1/Account" -H "accept: application/json"
But I keep getting a 404 error like below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /v1/Account</pre>
</body>
</html>
Not sure what am I doing wrong. Any help is highly appreciated !
Upvotes: 2
Views: 3410
Reputation: 2125
You don't need to provide the route like that, as it already is known by api versioning system.
First of all, you should configure api versioning, for example:
public void ConfigureServices( IServiceCollection services )
{
services.AddMvc();
services.AddApiVersioning(o => o.ApiVersionReader = new HeaderApiVersionReader("api-version"));
//and the rest
}
And then simple configuration:
services.AddApiVersioning(
o =>
{
o.AssumeDefaultVersionWhenUnspecified = true );
o.DefaultApiVersion = new ApiVersion( 1 );
} );
This will create default api version and assume that if no version is specified in request, default one will be taken under consideration.
Next your controller should look like that:
[ApiVersion( "1" )]
[Route( "api/mystuff" )]
public class mystuff1: Controller
{
[HttpGet]
public string Get() => "Mystuff1!";
}
[ApiVersion( "2" )]
[Route( "api/mystuff" )]
public class mystuff2 : Controller
{
[HttpGet]
public string Get() => "Mystuff2!";
}
Then just add header to your request: api-version: 2
(this is done by AddApiVersioning in ConfigureServices).
Upvotes: 4