[英]Swagger UI - Web API versioning when using Microsoft.AspNet.WebApi.Versioning
[英]Web API 2 versioning with Microsoft.AspNet.WebApi.Versioning
我正在使用ASP.NET版本控制庫 ,我已經按照步驟將這個庫添加到一個非常基本的ASP.NET Web API 2項目中,以下是我文件的內容: Global.asax
文件:
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
}
}
Web API配置:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.AddApiVersioning(c => c.AssumeDefaultVersionWhenUnspecified = true);
}
}
第一控制器:
namespace WebApplication5.Controllers
{
[ApiVersion("1.0")]
[RoutePrefix("api1")]
public class ValuesController : ApiController
{
[Route("values")]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
[Route("values/{id}")]
public string Get(int id)
{
return "value";
}
}
}
第二個控制器:
namespace WebApplication5.Controllers
{
[ApiVersion("2.0")]
[RoutePrefix("api1")]
[ControllerName("Values")]
public class ValuesController2 : ApiController
{
[Route("values")]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
[Route("values/{id}")]
// GET api/values/5
public string Get(int id)
{
return "value";
}
}
}
當我運行該應用程序並導航到該URL時: http://localhost:5428/api1/values?api-version=1.0
我得到了所需的結果,但是當我導航到該URL時: http://localhost:5428/api1/values?api-version=2.0
我遇到一條錯誤消息,指出No route providing a controller name with API version '2.0' was found to match request URI 'http://localhost:5428/api1/values'
,想知道我在此基本設置中缺少什么嗎?
如果我從ValuesController2
刪除[ControllerName]
屬性, ValuesController2
沒有任何變化,問題仍然存在。
我試圖更改第二個控制器的名稱空間,但是它也沒有解決問題!
我正在使用此庫的3.0.1版本。
剛意識到您的問題是什么,控制器名稱應該是Values2Controller
而不是ValuesController2
。
控制器使用名稱上的慣例進行定位,它刪除了控制器部分,但您的控制器部分是Controller2,因此我想根據您返回的消息找不到它。
不確定在控制器上具有ApiVersion屬性的有效性,但是在我的實現中,我在操作上具有該屬性,例如
[AllowAnonymous]
[Route("[controller]")]
[ApiController]
public class VersionDemoController
{
[ApiVersion("1.1")]
[HttpGet("requestStuff")]
public string RequestStuff()
{
return "Stuff using Version 1.1 API";
}
}
更新:剛剛嘗試在控制器上使用屬性,並且看起來工作正常,我的名稱空間不同,動作名稱相同。 我正在使用版本軟件包的3.1.2版本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.