在 aspnetboilerplate 中向我的宿主项目添加 API 控制器时 Swagger 中断 [英] Swagger breaks when adding an API Controller to my Host Project in aspnetboilerplate
问题描述
我从 https://aspnetboilerplate.com/Templates 下载了一个新的 .Net Core MVC 项目模板,设置一切(数据库和恢复的 nuget 包)并运行主机应用程序.一切都很好,因为我开始使用 Swagger UI 并且可以看到所有标准服务.
I downloaded a new .Net Core MVC project template from https://aspnetboilerplate.com/Templates, setup everything (database and restored nuget packages) and ran the Host application. All good as I get the Swagger UI going and can see all the standard services.
然后我继续在主机应用程序中创建一个简单的 API 控制器:
I then proceeded to create a simple API controller in the Host application:
[Route("api/[controller]")]
[ApiController]
public class FooBarController : MyAppControllerBase
{
public string HelloWorld()
{
return"Hello, World!";
}
}
然后 Swagger 无法加载 API 定义:
And then Swagger fails to load the API definition:
Fetch error
Internal Server Error http://localhost:21021/swagger/v1/swagger.json
如果我删除 Route
和 ApiController
属性,Swagger 会再次工作,但不会显示我的新控制器.我可以通过转到 http://localhost:21021/foobar/helloworld
来访问它,这可能没问题,但我希望它显示在 Swagger UI 中.
If I remove the Route
and ApiController
attributes, Swagger works again, but my new controller is not displayed. I can access it by going to http://localhost:21021/foobar/helloworld
which is probably fine, but I'd like it to show up in Swagger UI.
我错过了什么吗?
推荐答案
这是您应该如何在Configure(IApplicationBuilder app, IHostingEnvironment env)"方法中配置 Swagger.
This is how you should configure your Swagger in your "Configure(IApplicationBuilder app, IHostingEnvironment env)" method.
#region Swagger COnfiguration
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("swagger/v1/swagger.json", "Your class name");
c.RoutePrefix = string.Empty;
});
#endregion
这里是 swagger 的 configureServices 设置.
And here will be your configureServices settings for swagger.
services.AddSwaggerGen(config =>
{
config.SwaggerDoc("v1", new Info
{
Title = "Title Here",
Version = "v1"
});
});
这篇关于在 aspnetboilerplate 中向我的宿主项目添加 API 控制器时 Swagger 中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!