Swagger breaks when adding an API Controller to my Host Project in aspnetboilerplate

折月煮酒 提交于 2019-12-11 15:58:20

问题


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.

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!";
    }
}

And then Swagger fails to load the API definition:

Fetch error
Internal Server Error http://localhost:21021/swagger/v1/swagger.json

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.

Am I missing something?


回答1:


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

And here will be your configureServices settings for swagger.

services.AddSwaggerGen(config =>
{
    config.SwaggerDoc("v1", new Info
    {
        Title = "Title Here",
        Version = "v1"
    });
});


来源:https://stackoverflow.com/questions/56374657/swagger-breaks-when-adding-an-api-controller-to-my-host-project-in-aspnetboilerp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!