简体   繁体   中英

Simple Swagger generation with Swashbuckle

I needed to create some Swagger docs for another project so I wanted to quickly do it with Swashbuckle to save some time. In Visual studio I created a new Project with ASP.NET Core WEb Application and choose the Model-View-Controller template. I then installed Swashbuckle via Nuget and changed the template vales to these:

Program.cs

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

Startup.cs

 public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services
                .AddControllers()
                .AddJsonOptions(x =>
                {
                    x.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
                    x.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
                    x.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
                });

            services.AddSwaggerGen(x =>
            {
                x.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
                x.DescribeAllParametersInCamelCase();

                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                x.IncludeXmlComments(xmlPath);
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseSwagger(x => x.SerializeAsV2 = true);

            app.UseSwaggerUI(x =>
            {
                x.SwaggerEndpoint("/swagger/v1/swagger.json", "My API v1");
                x.RoutePrefix = string.Empty;
            });

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }

Controllers/ApiController.cs

[ApiController]
[Produces("application/json")]
[Consumes("application/json")]
[Route("api/MyApi/v1/")]
public class ApiController : Controller
{

    /// <summary>
    ///     Gets something as bytes for the given <paramref Id="id"/>.
    /// </summary>
    /// <returns>A result object indicating success or failure.</returns>
    /// <response code="200">The request succeeded.</response>
    /// <response code="400">
    ///     At least one of the following issues occurred:
    ///     - Error
    /// </response>
    /// <response code="500">An unexpected error occurred.</response>
    [HttpGet("{id}")]
    public static Task<Result> GetSomething(string id)
    {
        return new Task<Result>(null, "");
    }
}

Now when I launch the API and see the swagger, I get the "My API" name but there are no endpoints:

No operations defined in spec!

Why doesn't this work?

I think you need services.AddMvcCore() as well...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM