SoFunction
Updated on 2025-03-07

C# webapi method to configure swagger

How to configure swagger?

In the use project, we want to view our webapi tests, so we need to have an integrated test.

step

1. Download the swagger package in the nutget management package.

2. This will appear in the App_start folder and,
This is the time to configure.

3. Uncomment the following comment ()

 (("{0}/bin/", ));

Of course, for the purpose of modularization of the code, we can encapsulate it into a method:

private static string GetXmlCommentsPath()
{
  return $@"{}\bin\";
}

OK, ok, we know this configuration.

Then we need to create an xml in the bin directory, and the recommended project name is.xml.

4. Then the next step is configuration.

using System;
using ;
using ;
using ;
using ;
using ;
using ;
using ;

[assembly: (typeof(ThinkingSpace.App_Start.SwaggerNet), "PreStart")]
[assembly: (typeof(ThinkingSpace.App_Start.SwaggerNet), "PostStart")]
namespace ThinkingSpace.App_Start 
{
  public static class SwaggerNet 
  {
    public static void PreStart() 
    {
      (
        name: "SwaggerApi",
        routeTemplate: "api/docs/{controller}",
        defaults: new { swagger = true }
      );      
    }
    
    public static void PostStart() 
    {
      var config = ;

      (new SwaggerActionFilter());
      
      try
      {
        (typeof(IDocumentationProvider),
          new XmlCommentDocumentationProvider(("~/bin/")));
      }
      catch (FileNotFoundException)
      {
        throw new Exception("Please enable \"XML documentation file\" in project properties with default (bin\\) value or edit value in App_Start\\");
      }
    }
  }
}

To unify the location of the xml we need to modify.

Notice

We need to have only one get in webapi, otherwise an error will be reported because it needs to comply with the restful standard.

There can only be one HttpGet request in a controller, and if there are too many, an error will be reported. It is recommended to reduce overloading methods and separate other Get methods.

If you add (apiDescriptions => ()); in it, only the first get method will be displayed

Also: You can not install swagger ui for .net, and if installed, you may report an error.

The above is the detailed content of the method of configuring swagger in c# webapi. For more information about configuring swagger in c#, please follow my other related articles!