.net 6 web api adds api annotations to Swagger

  1. By default, our api has no annotations
    insert image description here

  2. Add xml comments above the api method
    insert image description here

  3. Configure Swagger in the Program.cs file, add the following code

builder.Services.AddSwaggerGen(c =>
{
    
    
    c.SwaggerDoc("v1", new OpenApiInfo {
    
     Title = "My API", Version = "v1" });
    var xmlFile = $"{
      
      Assembly.GetExecutingAssembly().GetName().Name}.xml";
    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
    c.IncludeXmlComments(xmlPath);
});

insert image description here

  1. Start the project and see the effect
    insert image description here

error problem

If the following error is reported at startup, it is because Swagger needs to access the XML comment file, but the file is not generated in your project. insert image description here
In order to generate this file, follow these steps:

  1. Right click on the project in Visual Studio and select Properties.
  2. Select the Generate tab. In the "Output" drop-down menu, tick "Generate a file containing API documentation".
  3. Save changes and rebuild the project.
    insert image description here

After rebuilding the project, the XML annotation files should be generated so that Swagger can access them.

Guess you like

Origin blog.csdn.net/weixin_44442366/article/details/129525623