我有一个全新的.NET-Core Web API项目,我希望使用API版本和swagger。
当我尝试查看swagger页面时,我得到了404.但是,模板附带的默认ValuesController可以正常工作。
这是我的设置:
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// Add API Versioning
services.AddApiVersioning(
options =>
{
options.DefaultApiVersion = new ApiVersion(1, 0);
options.AssumeDefaultVersionWhenUnspecified = true;
options.ReportApiVersions = true;
});
// Add Swagger
string pathToDoc = "RegistriesApi.xml";
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1",
new Info
{
Title = "Registries API",
Version = "v1",
Description = "A simple api to interact with AMA registries information",
TermsOfService = "None"
});
string filePath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, pathToDoc);
options.IncludeXmlComments(filePath);
options.DescribeAllEnumsAsStrings();
});
}
...
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// Url Path Rewriter
RewriteOptions rewriteOptions = new RewriteOptions();
if (!env.IsDevelopment())
{
rewriteOptions.AddRedirectToHttps();
}
else
{
app.UseDeveloperExceptionPage();
}
app.UseRewriter(rewriteOptions);
// Use MVC
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
// Swagger
app.UseSwagger(c =>
{
c.PreSerializeFilters.Add((swagger, httpReq) => swagger.Host = httpReq.Host.Value);
});
app.UseSwaggerUI(
c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "V1 Docs"); });
}
ValuesController.cs
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/values")]
public class ValuesController : Controller
{
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
return new[] {"value1", "value2"};
}
// GET api/values/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}
// POST api/values
[HttpPost]
public void Post([FromBody] string value)
{
}
// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
此外,这是我安装的所有库的版本:
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.8" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="2.2.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="2.4.0" />
</ItemGroup>
有谁看到我可能做错了什么?
答案 0 :(得分:6)
当我创建项目时,我意外地在登记时包含.vs文件夹。当我从源代码管理中删除它时,无论出于何种原因,swagger再次开始工作。
不确定解释是否适用于此。
答案 1 :(得分:0)
对我来说@Tyler Findlay 解决方案没有奏效。但我采用了一种对我来说很好用的不同方式。
希望这会对某人有所帮助。
更新:URL 可以是 HTTP://localhost:/swagger/ui