ASP. WEBAPI Document Swagger Depth optimization

Source: Internet
Author: User

This article copyright belongs to the blog park and the author Wu Di himself common all, reproduced and crawler Please indicate the blog park snail original address, Cnblogs.com/tdws

Write in front

Please forgive me this title party, wrote the 100th essay, said is the depth of optimization, in fact, there is no depth. The source code is also not modified, if you want to use WEBAPI swagger document, please first move to the previous one of the medium optimization.

First: ASP. WEBAPI document Swagger Moderate optimization http://www.cnblogs.com/tdws/p/6100126.html

Article Two: ASP. WebApi document Swashbuckle.core and Swaggerui depth customization

1. Document front and back end separation

2. Project Structure

3. Implement a sub-area (module) to filter the controller to be displayed

Document front and back end separation

This article provides source code, download link: https://github.com/coderws/CustomSwagger (because blog park can only upload 10MB, put on GitHub, do not ask for Star, only for the convenience of download)

Because Swagger original swagger page and resources JS CSS and other files are embedded in the DLL, although we can find Swagger UI source code, but still feel some inconvenience. So using GitHub on another open source project SOSOAPI, its document function is also based on swagger, but for us to have to expand, such as the ready-made Chinese and English switching category. And the resources are completely different from the previous embedded resources, the direct separation of a Swagger UI folder, including js,css,images,html and so on, so we can modify it very convenient to do what you want to customize, And I will swagger the background processing source down, add to the solution, later encountered problems, no longer have to receive DLL can not be modified and new features of the puzzle. You can use swagger as part of your framework.

Project structure

You can see Swashbuckle.core. Is Swagger's backstage source code, expands the test project, in which the Doc folder, is all the Swaggerui content, index.html is our document homepage:

Implement a split area (module) to filter the controller that you want to show

Again, the area group premise a little bit of change

required for striking red

Swagger maximum width increased to 1100px,

Add module filter to the left and click Filter to display only the corresponding module.

The specific way to do this is to filter the API access path based on your module name

As the first user, it represents the user module, and the second user is the controller name. Such a definition, using the new features of MVC5 Routeattribute and Routeprefixattribute, which they used to customize the route in the controller, you can download the source code to see.

So where is the data from our left-hand menu bar? See source Swaggerconfig, I define a method:

/// <summary>        ///Read the controller description from the API documentation/// </summary>        /// <returns>All controller Descriptions</returns>         Public Staticconcurrentdictionary<string,string> Getcontrollerdesc (hashset<string>modulelist) {            stringXmlpath = String.Format ("{0}/bin/swaggercustom.test.xml", AppDomain.CurrentDomain.BaseDirectory); Concurrentdictionary<string,string> controllerdescdict =Newconcurrentdictionary<string,string>(); if(File.exists (Xmlpath)) {XmlDocument xmldoc=NewXmlDocument (); XmlDoc.                Load (Xmlpath); stringType = String.Empty, Path = String.Empty, Controllername =String.Empty; string[] arrpath; intLength =-1, Ccount ="Controller".                Length; XmlNode Summarynode=NULL; foreach(XmlNode nodeinchXmlDoc. SelectNodes ("//member") ) {type= node. attributes["name"].                    Value; if(Type. StartsWith ("T:"))                    {                        //ControllerArrpath = type. Split ('.'); Length=arrpath.length; Controllername= Arrpath[length-1]; if(Controllername.endswith ("Controller"))                        {                            //Module Information                            varModuleName = Arrpath[length-2];                            Modulelist.add (ModuleName); //Get controller CommentsSummarynode = node. selectSingleNode ("Summary"); stringKey = Controllername.remove (Controllername.length-ccount, Ccount); if(Summarynode! =NULL&&! String.IsNullOrEmpty (summarynode.innertext) &&!Controllerdescdict.containskey (Key))                            {Controllerdescdict.tryadd (Key, SummaryNode.InnerText.Trim ()); }                        }                    }                }            }            returncontrollerdescdict; }

This method is used only to read the controller comment, but since it reads XML, I don't need to read it again. I have added a parameter of type hashset<string>, the data of each element in the collection is unique, so use it to save the module information, each time the XML traversal to the controller, I will read its modules information (such as namespace SwaggerCustom.Test.Controllers.Admin.AdminRoleController), then the second-to-last word is the module name. So our module information is also included in the JSON, see Areadescription, he explained that I have three modules.

Then the next step is to do the screen before the rendering of the work. I first guessed that the render must have something to do with the path (interface path) in the json, so I searched for path in swagger-ui-ext.js, and I finally found the result:

As shown below: When traversing, by filtering the module modules, I return directly to the module that does not conform to what I want, without going down and finally achieving the desired purpose. The reason why I did not do depth optimization is also here, the real depth optimization should be filtered in the background code, only return the JSON results you want, lazy.

So, I clicked the admin option to filter the results, only two controllers under the module.

For my personal added JS code, in Doc/lib/swagger-custom.js.

//Get Controller DescriptionfunctionSwaggercustom () { This. setcontrollersummary =function() {$.ajax ({type:"Get", Async:true, URL: $ ("#input_baseUrl"). Val (), DataType:"JSON", Success:function(data) {varSummarydict =data.                Controllerdesc; varID, 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"). Prepend (' <li style= "color:red;" class= "Controller-summary" title= "' + Strsummary + ' > ' + strsummary + ' </li> ');                }                    }                }); Swaggercustom.loadmenu (data.                Areadescription); Expendtoggle ();//Register Menu Shrink Events            }        });    }; //get current parameter     This. getquerystring =function(name) {varReg =NewRegExp ("(^|&)" + name + "= ([^&]*) (&|$)"); varr = Window.location.search.substr (1). Match (REG); if(r! =NULL)returnUnescape (r[2]);return NULL; },     This. LoadMenu =function(modules) {varURL =window.location.href; URL= url.substring (0, Url.lastindexof ('? '))); $(' body '). Prepend (' <div class= "Menu-expender" id= "menuexpend" >←</div><div id= "Modulemenu" ><div Onclick= "Menuclick (This)" data-url= "' + URL + '? Module=all" "data-module=" All "class=" Menu-inner "> All </div>& Lt;/div> '); varMenuinner = ' '; Modules.foreach (function(item) {Menuinner+ = ' <div onclick= ' Menuclick (This) "data-url=" ' + URL + '? module= ' + item.tolowercase () + ' "data-module=" ' + Item.tolow Ercase () + ' "class=" Menu-inner "> ' + Item + ' </div> ';        }); $(' #moduleMenu '). Append (Menuinner); $(' #moduleMenu '). CSS ("position", "fixed"). CSS ("Top", "20%"); }}varSwaggercustom =NewSwaggercustom ();varSwaggercustomglobaldata ={currentmodule:"All"}$(function() {Swaggercustomglobaldata.currentmodule= swaggercustom.getquerystring (' module ') = =NULL? "All": swaggercustom.getquerystring (' module ')); //alert (swaggercustomglobaldata.currentmodule);});varSwaggerstyle ={showactionlink:function () {        $("Li. Toggleendpointlist"). CSS ("Color", "#2392f7"); }, TitleStyle:function () {        $("H2. Toggleendpointlist"). CSS ("Color", "green")); }, Showdetaillink:function () {        $("Li. Expandresource"). CSS (' color ', ' #996633 ')); }, Paramtable:function () {        $('. Fullwidth.parameters thead tr th:nth-child (1) '). Width (' 50px '); $('. Fullwidth.parameters thead tr th:nth-child (2) '). Width (' 350px '); $('. Fullwidth.parameters thead tr th:nth-child (3) '). Width (' 100px '); $('. Fullwidth.parameters thead tr th:nth-child (4) '). Width (' 60px '); $('. Fullwidth.parameters thead tr th:nth-child (5) '). Width (' 400px '); $(' TD textarea '). Width (' 380px '); }, Init:function () {         This. Showactionlink ();  This. TitleStyle ();  This. Showdetaillink (); //this.paramtable ();    }}functionMenuclick (ele) {window.location.href=(Ele.dataset.url);}functionExpendtoggle () {$ (' #menuExpend '). Toggle (function () {        $( This). html (' → '); $(' #moduleMenu '). Hide (); }, function () {        $( This). html (' ← '); $(' #moduleMenu '). Show (); });}

How do I use it??

use direct copy to move SwaggerConfig.cs and Doc files to your project, and reference swashbuckle is no problem (you can take the source class library directly or install it directly from NuGet). And you want to use this module partition function, must conform to the routing rule api/modulename/controller/action. Because the filter of the module is through ModuleName. If you only want to use the basic functions of swagger, it is enough to share with one piece. Get this share of the source code, you can in which reasonable to modify the source code, customize your function

Written in the last

Still please forgive me for this title party.

If I share a bit of help to you, welcome to the red button below the attention, I will continue to output share. Also welcome for me, also for your own praise. About this source code has any questions, welcome message.

ASP. WEBAPI Document Swagger Depth optimization

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.