C#webapi Swagger online Document output parameters and input parameters display comments

Source: Internet
Author: User
Tags response code

The recent development of the WEBAPI need to generate online documentation, found that the document is not annotated, the online search is not complete, or look difficult to understand.

Took a little time to get out of this, a lot of it is to learn from the online data collation, easy to understand small white dedicated.

As shown in the final effect

1. Define a Swaggercontrollerdescprovider implementation Iswaggerprovider interface

Using swashbuckle.swagger;using system;using system.collections.concurrent;using system.collections.generic;using System.io;using system.linq;using system.web;using system.xml;namespace nop.web.app_start{//<summary>//s Description of the Wagger display Controller///</summary> public class Swaggercontrollerdescprovider:iswaggerprovider {privat        e readonly Iswaggerprovider _swaggerprovider; private static concurrentdictionary<string, swaggerdocument> _cache =new concurrentdictionary<string,        Swaggerdocument> ();        Private readonly string _xml;        <summary>/////</summary>/<param name= "Swaggerprovider" ></param> <param name= "xml" >xml document path </param> public Swaggercontrollerdescprovider (Iswaggerprovider swag            gerprovider,string xml) {_swaggerprovider = Swaggerprovider;        _xml = XML; } Public swaggerdocument Getswagger (string rooturl, string apiversion) {var CacheKey = string.            Format ("{0}_{1}", Rooturl, apiversion);            Swaggerdocument srcdoc = null; Read only once if (!_cache.                TryGetValue (CacheKey, out Srcdoc)) {Srcdoc = _swaggerprovider.getswagger (Rooturl, apiversion); Srcdoc.vendorextensions = new dictionary<string, object> {"Controllerdesc", Getcontrollerdesc ()}                }; _cache.            TryAdd (CacheKey, Srcdoc);        } return Srcdoc; }///<summary>//Read the controller description from the API documentation///</summary>//<returns> All controller descriptions &LT;/R Eturns> public concurrentdictionary<string, string> Getcontrollerdesc () {string Xmlpat            h = _xml;            concurrentdictionary<string, string> controllerdescdict = new concurrentdictionary<string, string> (); if (file.exists (Xmlpath)) {XmlDocument xmldoc = new XMLDocument (); XmlDoc.                Load (Xmlpath); String type = string. Empty, Path = string. Empty, Controllername = string.                Empty;                String[] Arrpath; int length =-1, ccount = "Controller".                Length;                XmlNode summarynode = null; foreach (XmlNode node in xmldoc. SelectNodes ("//member")) {type = node. attributes["Name"].                    Value; if (type. StartsWith ("T:")) {//Controller Arrpath = type.                        Split ('. ');                        length = Arrpath.length;                        Controllername = Arrpath[length-1];                            if (Controllername.endswith ("Controller")) {//Get Controller comments Summarynode = node.                            selectSingleNode ("Summary");            String key = Controllername.remove (Controllername.length-ccount, ccount);                if (Summarynode! = null &&!string.                                IsNullOrEmpty (Summarynode.innertext) &&!controllerdescdict.containskey (key)) {                            Controllerdescdict.tryadd (Key, SummaryNode.InnerText.Trim ());        }}}}} return controllerdescdict; }    }}

  

2. Define a JS file, make embedded resources, the function of this JS file is mainly two, one is Chinese, the other is to display the controller's descriptive text on the interface

' Use strict '; window.        Swaggertranslator = {_words: [], Translate:function () {var $this = this;            $ (' [data-sw-translate] '). each (function () {$ (the). HTML ($this. _trytranslate ($ (this). html ()));            $ (this). Val ($this. _trytranslate ($ (this). Val ()));        $ (this). attr ("title", $this. _trytranslate ($ (this). attr (' title ')));    });  }, Setcontrollersummary:function () {$.ajax ({type: "Get", Async:true, URL: $ ("#input_baseUrl"). Val (), DataType: "JSON", success:function (data) {var summaryd ICT = data.                Controllerdesc;                var id, controllername, strsummary;                    $ ("#resources_container. Resource"). each (function (i, item) {id = $ (item). attr ("id");                        if (id) {controllername = id.substring (9);                        Strsummary = Summarydict[controllername]; if (STRsUmmary) {$ (item). Children (". Heading"). Children (". Options"). First (). prepend (' <li class= ' cont                        Roller-summary "title=" ' + strsummary + ' "> ' + strsummary + ' </li> ');            }                    }                });    }        });  }, _trytranslate:function (word) {return This._words[$.trim (word)]!== undefined? This._words[$.trim (word)]:    Word    }, Learn:function (wordsmap) {this._words = Wordsmap; }};/* jshint quotmark:double */window. Swaggertranslator.learn ({"warning:deprecated": "Warning: Obsolete", "Implementation Notes": "Implementation Notes", "Response Class": "Response class "," status ":" State "," Parameters ":" Parameters "," Parameter ":" Parameter "," Value ":" Value "," Description ":" description "," Parameter Type ":" Parameter Type "," Data type ":" DataType "," Response Messages ":" Response message "," HTTP status Code ":" http "," Reason ":" Cause " , "Response model": "Response Models", "Request URL": "Requesting url", "Response Body": "Response Body", "Response CodE ":" Response Code "," Response Headers ":" Response header "," Hide Response ":" Hide Response "," Headers ":" header "," Try It out! ":" Try it! "," Show/hide ":" Show/Hide "," List Operations ":" Show Actions "," Expand Operations ":" Expand Operation "," raw ":" Raw "," can "T parse  Json. Raw result ":" Could not parse json.  Original result "," Model Schema ":" Schema "," model ":" Models "," Apply ":" Application "," Username ":" username "," Password ":" Password "," Terms of service ":" Terms "," Created by ":" Creator "," See More at ":" View more: "," Contacts the developer ":" Contact developer "," API vers Ion ": API Version", "Response content Type": "Response Content Type", "Fetching resource": "Getting Resources", "Fetching resource list" : "Getting Resource List", "Explore": "Browse", "show Swagger Petstore Example APIs": "Show Swagger Petstore Sample APIs", "Can ' t read f  Rom server. It may not have the appropriate access-control-origin settings. ":" Could not be read from the server. Access-control-origin may not be set correctly. "," Specify the protocol for ":" Specify protocol: "," can ' t read swagger json from ":" Cannot read swagger json in "," finished Lo Ading REsource information. Rendering Swagger UI ":" The resource information is loaded. Rendering swagger UI "," Unable to read API ":" Cannot read API "," From Path ":" Slave Path "," Server Returned ":" Server Returned "}); $ (function () {window.    Swaggertranslator.translate (); Window. Swaggertranslator.setcontrollersummary ();});

  

3. Modify the SwaggerConfig.cs file in App_start, the main code has two lines

C.customprovider ((defaultprovider) = new Swaggercontrollerdescprovider (defaultprovider,xmlfile));

. Enableswaggerui (c = c.injectjavascript (thisassembly, "test.webapi.scripts.swagger-custom.js"));

Test.webapi.scripts.swagger-custom.js This is the resource file that we defined in the second step, and the name of the resource file name is the following: The namespace of the project where the file is located. file path. FileName

The final code is as follows

public static void Register () {var xmlfile = string.            Format ("{0}/bin/test.webapi.xml", System.AppDomain.CurrentDomain.BaseDirectory); #region Native configuration var thisassembly = typeof (Swaggerconfig).            Assembly; Globalconfiguration.configuration.                        Enableswagger (c + = {c.includexmlcomments (Getxmlcommentspath ("Test.model")); C.singleapiversion ("v1", "Test.webapi").                        Description ("content");                        Sets the interface description XML Path address c.includexmlcomments (xmlfile);                        C.resolveconflictingactions (apidescriptions = Apidescriptions.first ()); Wrap the default Swaggergenerator with additional behavior (e.g. caching) or provide a//a                        Lternative implementation for Iswaggerprovider with the customprovider option.    //                    C.customprovider (defaultprovider) = new InformationApp.WebApi.App_Start.SwaggerControllerDescProv                        Ider (defaultprovider, xmlfile));                    C.resolveconflictingactions (apidescriptions = Apidescriptions.first ()); })                . Enableswaggerui (c + = {C.injectjavascript (thisassembly, "TEST.WEBAPI.AREAS.S So.                    Content.js.swagger-custom.js ");            }); #endregion} private static string Getxmlcommentspath (string name) {return string. Format ("{0}/bin/{1}.        XML ", System.AppDomain.CurrentDomain.BaseDirectory, name); }

  

It's important to note that

C.includexmlcomments (Getxmlcommentspath ("Test.model"));

The parameter in this Test.model is the namespace name of the model class where the interface input and output parameters are located

and Test.model to generate XML when this class library is generated.

As shown, click the Test.model Class Library right Button property

Tick the content in the red box

Do not understand the things to find more information is still very useful, thanks to the blog previous written by the predecessors of the experience

The above content is referenced from

Https://www.cnblogs.com/94pm/p/8046580.html

Https://www.cnblogs.com/liangxiarong/p/7768431.html

I'm just tidying up and making it easier for newbies to see.

C#webapi Swagger online Document output parameters and input parameters display comments

Related Article

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.