In Web Api 2.0, Swagger is used to generate two small Tips of the Api documentation.
How to add the Authorization request header to Swagger when Web Api 2.0 uses oau22?
Swagger instructions Support Manual Api calls. However, when the Api uses oau22authorization, the response result is always 401 unauthorized because there is no authorization Token input.
Public class AddAuthorizationHeader: IOperationFilter {// <summary> // Adds an authorization header to the given operation in Swagger. /// </summary> /// <param name = "operation"> The Swashbuckle operation. </param> /// <param name = "schemaRegistry"> The Swashbuckle schema registry. </param> /// <param name = "apide.pdf"> The Swashbuckle api description. </param> public void Apply (Operation operation, SchemaRegistry schemaRegistry, apide=apide.pdf) {if (operation = null) return; if (operation. parameters = null) {operation. parameters = new List <Parameter> ();} var parameter = new Parameter {description = "Token", @ in = "header", name = "Authorization", required = true, type = "string"}; if (apide.pdf. actionDescriptor. getCustomAttributes <AllowAnonymousAttribute> (). any () {// If the Api method permits anonymous methods, the Token is not a required parameter. required = false;} operation. parameters. add (parameter );}}
2. enable Authorization request headers in SwaggerConfig. cs.
public static void Register(HttpConfiguration config) { var thisAssembly = typeof(SwaggerConfig).Assembly; config.EnableSwagger(c => { c.OperationFilter<AddAuthorizationHeader>(); c.SingleApiVersion("v1", "EHealthCareClinic.WebApi"); c.IncludeXmlComments(GetXmlCommentsPath()); }) .EnableSwaggerUi(c => { }); }
3. Compile the Api project and re-open the Swagger instruction. The Authorization variable will appear in the Parameters list, enter the correct Authorization Token, And the 401 unauthorized question disappears.
/// <Summary> /// obtain the province list /// <param name = "countryId"> country ID </param> /// </summary> [HttpGet] [route ("countries/{countryId}/provinces")] public IHttpActionResult GetProvinceList (Guid countryId) {var result = QueryService. getProvinceCollection (new CountryId (countryId); return OK (result );}
/// <Summary> /// obtain the province list /// <param name = "countryId"> country ID </param> /// </summary> [HttpGet] [route ("countries/{countryId}/provinces")] [ResponseType (typeof (IEnumerable <EHealthCareClinic. business. queryModel. provincePresentation>)] public IHttpActionResult GetProvinceList (Guid countryId) {var result = QueryService. getProvinceCollection (new CountryId (countryId); return OK (result );}