I am trying to get Web API versioning working with an inherited class. I am working with two very simple variations of the stock Values controller.
[ApiVersion("1.0")]
[RoutePrefix("api/v{version:apiVersion}/Values")]
[ControllerName("Values")]
public class ValuesController : ApiController
{
// GET api/values
[Route("")]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
[Route("{id:int}")]
public virtual string Get(int id)
{
return "value from 1";
}
}
[ApiVersion("2.0")]
[RoutePrefix("api/v{version:apiVersion}/Values")]
[ControllerName("Values")]
public class Values2Controller : ValuesController
{
//Want to use the method in the base class
//public IEnumerable<string> Get()
//{
// return new string[] { "value2-1", "value2-2" };
// }
[Route("{id:int}")]
// GET api/values/5
public new string Get(int id)
{
return "value from 2";
}
}
My start up configuration is also pretty straightforward.
public static void Register(HttpConfiguration config)
{
var constraintResolver = new DefaultInlineConstraintResolver()
{
ConstraintMap = {["apiVersion"] = typeof(ApiVersionRouteConstraint)}
};
config.MapHttpAttributeRoutes(constraintResolver);
config.AddApiVersioning(o => { o.AssumeDefaultVersionWhenUnspecified = true; });
}
The non-overridden routes work exactly as I would expect
http://localhost:32623/api/v1.0/Values/12 -> "value from 1"
http://localhost:32623/api/v2.0/Values/12 -> "value from 2"
Calling v1 of the default Get Route
http://localhost:32623/api/v1.0/Values -> Value1, Value2
However trying the same route on the child controller results in an error.
http://localhost:32623/api/v2.0/Values
<Message>
The HTTP resource that matches the request URI 'http://localhost:32623/api/v2.0/Values' does not support the API version '2.0'.
</Message>
<InnerError>
<Message>
No route providing a controller name with API version '2.0' was found to match request URI 'http://localhost:32623/api/v2.0/Values'.
</Message>
</InnerError>
The error message suggests that the overridden member expects a "1.0" route and I am able to work around this with a method like this in the child class.
[Route("")]
public override IEnumerable<string> Get()
{
return base.Get();
}
But this seems less than ideal across a larger application. Is there a way to make this work the way I would like, without these "empty" overrides?