In some REST web APIs, you need to send mandatory data in the request header to access API methods. For example, user data. Because of that, we need to configure SwaggerUI as well so that it has a section to insert header request details/parameters and users are able to access methods in the SwaggerUI.
For this example, I used Swashbuckle.AspNetCore 5.0.0-rc2. To install :
Package Manager : Install-Package Swashbuckle.AspNetCore
First, you need to create a filter class with IOperationFilter implemented. In that, you can specify the header request parameter as follows:
public class HeaderFilter : IOperationFilter { public void Apply(OpenApiOperation operation, OperationFilterContext context) { if (operation.Parameters == null) operation.Parameters = new List(); operation.Parameters.Add(new OpenApiParameter { Name = "U-GUID", // Request header name In = ParameterLocation.Header, // Type of the parameter Description = "User GUID", // Description of the parameter Required = true, // Whether it is mandatory or not Schema = new OpenApiSchema // Parameter variable format { Type = "string" } }); } }
After that, we need to say to SwaggerUI to use this class an OperationFilter. That should be done in the ConfigureServices() in Startup.cs class.
// Register the Swagger generator, defining 1 or more Swagger documents services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Version = "v1", Title = "Vetserve Public Api Connector", Description = "API to access Government Animal Registry Data.", }); c.OperationFilter<HeaderFilter>(); // Set the comments path for the Swagger JSON and UI. var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); c.DescribeAllEnumsAsStrings(); });
Once that is done, you are good to use the API method in SwaggerUI.
Leave a comment