2 Tips for building API documentation using swagger in WEB API 2.0

Source: Internet
Author: User

When Web API 2.0 uses OAuth2 authorization, how do I add a authorization request header to swagger?

The swagger documentation supports the manual invocation of the API, but when the API uses OAUTH2 authorization, there is no place to enter the authorization token, causing the response to be 401 without authorization.

Solution:

In the Swagger configuration file, add the settings for authorization in the request header.

1. Add a new class Addauthorizationheader and implement the Ioperationfilter interface in the API project

 Public classAddauthorizationheader: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= "Apidescription" >The swashbuckle API description.</param>         Public voidApply (Operation operation, Schemaregistry Schemaregistry, apidescription apidescription) {if(Operation = =NULL)return; if(Operation.parameters = =NULL) {operation.parameters=NewList<parameter>(); }            varparameter =NewParameter {Description="Token", @in="Header", name="Authorization", Required=true, type="string"            }; if(apidescription.actiondescriptor.getcustomattributes<allowanonymousattribute>(). Any ()) {//if the API method is to allow anonymous methods, token is not requiredparameter.required=false;        } operation.parameters.Add (parameter); }    }

2. Enable the authorization request header in SwaggerConfig.cs.

         Public Static voidRegister (httpconfiguration config) {varthisassembly =typeof(Swaggerconfig).            Assembly; Config. Enableswagger (c={C.operationfilter<AddAuthorizationHeader>(); C.singleapiversion ("v1","Ehealthcareclinic.webapi");            C.includexmlcomments (Getxmlcommentspath ()); })            . Enableswaggerui (c=            {            }); }

3. Compile the API project, reopen the swagger documentation, the parameters list will appear authorization variables, enter the correct authorization token, 401 unauthorized issues disappear.

How do I generate the response class example in Swagger when Web Api 2.0 uses Ihttpactionresult as the return value?

Ihttpactionresult is the interface introduced by Web API 2.0.

The benefit of using Ihttpactionresult as the API return value.

    • Simplifies unit testing of the Controller
    • Common logic for creating HTTP responses is moved to a separate class
    • Make the controller move more clearly by hiding the underlying details

The swagger document is generated by reading the XML document description file generated by the Web API project and using reflection technology to dynamically demonstrate the method signature of each action method.

However, after using Ihttpactionresult as the API method return value, swagger cannot correctly read the type of the return value through reflection, so the resulting document is missing.

Cases:

        /// <summary>        ///get list of provinces/// <param name= "Countryid" >Country ID</param>        /// </summary>[HttpGet] [Route ("countries/{countryid}/provinces")]         Publicihttpactionresult getprovincelist (Guid Countryid) {varresult = Queryservice.getprovincecollection (NewCountryid (Countryid)); returnOk (Result); }

Solution Solutions :

A new attribute class System.Web.Http.Description.ResponseTypeAttribute is introduced in Web API 2.0.

This attribute class constructs only one parameter, which is the type of the return value.

We only need to declare the type of the API return value using this new feature at each API method signature, and a description of the return type appears in the swagger generated description document.

        /// <summary>        ///get list of provinces/// <param name= "Countryid" >Country ID</param>        /// </summary>[HttpGet] [Route ("countries/{countryid}/provinces")] [Responsetype (typeof(ienumerable<ehealthcareclinic.business.querymodel.provincepresentation>))]         Publicihttpactionresult getprovincelist (Guid Countryid) {varresult = Queryservice.getprovincecollection (NewCountryid (Countryid)); returnOk (Result); }

2 Tips for building API documentation using swagger in WEB API 2.0

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.