我有一个使用默认值控制器的基本WebApi实现设置。
reading a blog about RESTful WebApi Versioning之后我决定将软件包集成到一个新的WebApi项目中。
我已经添加了NuGet包Microsoft.AspNet.WebApi.Versioning来协助我的API版本控制。以下是我所遵循的包配置说明的URL:
https://github.com/Microsoft/aspnet-api-versioning/wiki/Configuring-Your-Application
我的价值观控制器非常简单。我已经将装饰添加到了我的Get方法中。这是代码:
[Authorize]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/values")]
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
不幸的是,只要我将以下代码行添加到控制器中,整个事情就会爆发:
[Route("api/v{version:apiVersion}/values")]
以下是查看正在返回的错误消息:
The inline constraint resolver of type 'DefaultInlineConstraintResolver' was unable to resolve the following inline constraint: 'apiVersion'.
Line 82: GlobalConfiguration.Configure(WebApiConfig.Register);
以下是我在Startup.cs中的代码
public void Configuration(IAppBuilder app)
{
// HTTP Configuration
HttpConfiguration config = new HttpConfiguration();
//config.MapHttpAttributeRoutes();
// Configure API Versioning
config.AddApiVersioning();
var constraintResolver = new DefaultInlineConstraintResolver()
{
ConstraintMap =
{
["apiVersion"] = typeof( ApiVersionRouteConstraint ) // or mvc routing?
}
};
config.MapHttpAttributeRoutes(constraintResolver);
// Configure the API to accept token authentication
ConfigureOAuthTokenConsumption(app);
// CORS
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
// Configure the Authorization server
ConfigureOAuth(app);
// Use WebAPI
app.UseWebApi(config);
// Moved from global.asax
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
我认为调用AddApiVersioning并提供文档中概述的constraintResolver可以解决问题,但事实并非如此。现在我正在努力做下一步该做什么。
config.AddApiVersioning();
var constraintResolver = new DefaultInlineConstraintResolver()
{
ConstraintMap =
{
["apiVersion"] = typeof( ApiVersionRouteConstraint ) // or mvc routing?
}
};
config.MapHttpAttributeRoutes(constraintResolver);
有什么建议吗?
答案 0 :(得分:16)
您应该解析WebApiConfig.cs文件中的版本
var constraintResolver = new DefaultInlineConstraintResolver()
{
ConstraintMap =
{
["apiVersion"] = typeof( ApiVersionRouteConstraint )
}
};
config.MapHttpAttributeRoutes(constraintResolver);
在映射路线之前。我的意思是在config.Routes.MapHttpRoute()
之前