我在一个解决方案中包含了asp.net核心MVC项目和独立的WebApi项目。我在github上的文档之后添加了swagger。这是我的mvc项目的Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
//...
// Adding controllers from WebApi:
var controllerAssembly = Assembly.Load(new AssemblyName("WebApi"));
services.AddMvc(o =>
{
o.Filters.Add<GlobalExceptionFilter>();
o.Filters.Add<GlobalLoggingFilter>();
})
.AddApplicationPart(controllerAssembly)
.AddJsonOptions(options =>
{
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
services.AddSwaggerGen(c =>
{
//The generated Swagger JSON file will have these properties.
c.SwaggerDoc("v1", new Info
{
Title = "Swagger XML Api Demo",
Version = "v1",
});
});
//...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//...
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Swagger XML Api Demo v1");
});
//...
app.UseMvc(routes =>
{
// ...
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
下面是一些小细节:
WebApi控制器属性路由:
[Route("api/[controller]")]
public class CategoriesController : Controller
{
// ...
[HttpGet]
public async Task<IActionResult> Get()
{
return Ok(await _repo.GetCategoriesEagerAsync());
}
// ...
}
当我尝试访问/swagger时,它找不到/swagger/v1/swagger.json:
我哪里做错了?
提前感谢!
发布于 2018-11-27 18:44:25
我被这个问题困扰了好几个小时。我找到了原因..。
检查下面的代码!!
..Startup.cs..
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
app.UseSwagger(); // if I remove this line, do not work !
app.UseSwaggerUi3();
}
发布于 2019-08-06 13:52:42
我也想在这里补充一下我的经验。我在configureServices
中给出的版本是V1
(注意大写的V
)和
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", //this v was in caps earlier
new Swashbuckle.AspNetCore.Swagger.Info
{
Version = "v1",//this v was in caps earlier
Title = "Tiny Blog API",
Description = "A simple and easy blog which anyone love to blog."
});
});
//Other statements
}
然后在configure
方法中,它是小写的
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Tiny Blog V1");
});
}
也许它能帮助某些人。
发布于 2022-01-17 01:30:59
检查您是否正确设置了环境,以及命令app.UseSwagger
是否不在if中,以便仅在确定的环境(如开发)上执行。
测试解决方案是在任何条件语句之外添加行app.UseSwagger(
)。
https://stackoverflow.com/questions/52162321
复制相似问题