我最近在我的项目中引入了Microsoft.AspNet.WebApi.Versioning
(github)软件包,以对API进行版本控制。
它的工作原理像一种魅力,但不幸的是,它具有怪异的副作用。它将IEnumerable<T>
uri参数的默认参数值从null
更改为空的List<T>
。我使用软件包存储库中的基本示例将其隔离。
致电http://localhost:xxx/api/v1/helloworld返回
ids is null: True
,如果未启用了版本控制(以前的行为)
ids is null: False
(如果启用了版本控制)
恐怕它也会改变其他行为。如何保留版本功能,但使用默认的模型绑定?
控制器
// breaks
[Microsoft.Web.Http.ApiVersion("1.0")]
[RoutePrefix( "api/v{version:apiVersion}/helloworld" )]
// working
//[RoutePrefix("api/v1/helloworld")]
public class HelloWorldController : ApiController
{
[Route]
public IHttpActionResult Get([FromUri] IEnumerable<Guid> ids)
{
return Ok($"ids is null: {ids == null}");
}
}
设置
public class Startup
{
public void Configuration( IAppBuilder builder )
{
var configuration = new HttpConfiguration();
var httpServer = new HttpServer( configuration );
// breaks:
configuration.AddApiVersioning();
var constraintResolver = new DefaultInlineConstraintResolver() { ConstraintMap = { ["apiVersion"] = typeof(ApiVersionRouteConstraint) } };
configuration.MapHttpAttributeRoutes(constraintResolver);
// defaut (works)
//configuration.MapHttpAttributeRoutes();
builder.UseWebApi( httpServer );
}
}
复制
git clone https://github.com/smstuebe/webapi-versioning-parameter-binding.git
git checkout working
# if you want to break it
git checkout broken