ASP. Webapi using swagger to generate test documents

Source: Internet
Author: User
Tags response code

ASP. Webapi using swagger to generate test documents

Swaggerui is a simple RESTful API testing and documentation tool. Simple, beautiful, easy to use (official demo). Displays the API by reading the JSON configuration. The project itself only relies on some html,css,js static files. You can use it on almost any web container

For a long time the final effect is as follows

1. API Controller and action description

2. Test interface

Using swagger

1. Create a WEBAPI project solution

2. Reference Swagger NuGet Package

Swashbuckle and Swagger.net

Remove the extra Swaggerui folder and configuration class Swaggernet

3. Add interface annotations

Next you can access Http://xxxx/swagger so that you don't see the annotations

Item properties, tick generate XML document file

Modify the Swaggerconfig file

C.includexmlcomments (String. Format (@ "{0}\app_data\api.xml", AppDomain.CurrentDomain.BaseDirectory));

Chinese

1.SwaggerConfig

JS file needs to be embedded in the DLL

<summary>
Chinese conversion
</summary>
var Swaggertranslator = (function () {
Timed execution detection is converted to Chinese, up to 500 times 500*50/1000=25s
var iexcute = 0,
Chinese language Pack
_words = {
"warning:deprecated": "Warning: Obsolete",
"Implementation Notes": "Implementation Notes",
"Response class": "Response Class",
"Status": "State",
"Parameters": "Parameters",
"Parameter": "Parameters",
"Value": "Values",
"Description": "description",
"Parameter type": "Parameter Type",
"Data type": "DataType",
"Response Messages": "Response message",
"HTTP status Code": "HTTP state Codes",
"Reason": "Cause",
"Response Model": "Response Models",
"Request URL": "Requesting URL",
"Response Body": "Response body",
"Response Code": "Response Code",
"Response Headers": "Response header",
"Hide Response": "Hidden Response",
"Headers": "Head",
"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": "Modeling Architecture",
"Model": "Models",
"Apply": "Apply",
"Username": "User name",
"Password": "Password",
"Terms of Service": "TOS",
"Created by": "Creator",
"See more at": "View more:",
"Contact the developer": "Contacting the developer",
"API Version": "API Versions",
"Response Content Type": "Response content Type",
"Fetching resource": "Getting Resources",
"Fetching resource List": "Getting a listing of resources",
"Explore": "Browse",
"Show Swagger Petstore Example APIs": "Show Swagger Petstore sample APIs",
"Can ' t read from 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. ",
"Please specify the protocol for": "Specify protocol:",
"Can ' t read swagger json from": "Cannot read swagger json in",
"Finished Loading Resource information. Rendering Swagger UI ":" The resource information is loaded. Rendering Swagger UI ",
"Unable to read API": "Unable to read API",
' From path ': ' From Path ',
"Click to set as parameter value": "Click Set Parameters",
"Server returned": "Servers returned"
},

Perform conversions on a timed basis
_TRANSLATOR2CN = function () {
if ($ ("#resources_container. Resource"). Length > 0) {
_trytranslate ();
}

if ($ ("#explore"). Text () = = "Explore" && Iexcute < 500) {
iexcute++;
SetTimeout (_TRANSLATOR2CN, 50);
}
},

//Set Controller comment
_setcontrollersummary = function () {
$.ajax ({
Type: "Get",
async:true,
URL: $ ("#input_ BaseUrl "). Val (),
DataType:" JSON ",
Success:function (data) {
var summarydict = data. Controllerdesc;
Var id, controllername, strsummary;
$ ("#resources_container. Resource"). each (function (i, item) {
ID = $ (item). attr ("id");
if (id) {
controll Ername = id.substring (9);
Strsummary = Summarydict[controllername];
if (strsummary) {
$ (item). Children (". Heading"). Children (". Options"). Prepend (' <li class= '). Controller-summary "title=" ' + strsummary + ' "> ' + strsummary + ' </li> ');
}
}
});
}
});
},

Try to convert English into Chinese
_trytranslate = function () {
$ (' [data-sw-translate] '). each (function () {
$ (this). HTML (_GETLANGDESC ($ (this). html ()));
$ (this). Val (_getlangdesc ($ (this). Val ()));
$ (this). attr (' title ', _getlangdesc ($ (this). attr (' title ')));
});
},
_getlangdesc = function (word) {
return _words[$.trim (word)]!== undefined? _words[$.trim (word)]: word;
};

return {
Translator:function () {
Document.title = "API description document";
$ (' body '). Append (' <style type= "Text/css" >.controller-summary{color: #10a54a!important;word-break:keep-all; White-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:250px;text-align:right;cursor:default;} </style> ');
$ ("#logo"). HTML ("interface description"). attr ("href", "/home/index");
Setting the controller description
_setcontrollersummary ();
_TRANSLATOR2CN ();
}
}
})();
Performing conversions
Swaggertranslator.translator ();

2. Controller description and interface document caching

public class Cachingswaggerprovider:iswaggerprovider
{
private static concurrentdictionary<string, swaggerdocument> _cache =
New concurrentdictionary<string, swaggerdocument> ();

Private ReadOnly Iswaggerprovider _swaggerprovider;

Public Cachingswaggerprovider (Iswaggerprovider swaggerprovider)
{
_swaggerprovider = Swaggerprovider;
}

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 description </returns>
public static concurrentdictionary<string, string> Getcontrollerdesc ()
{
String xmlpath = string. Format (@ "{0}\app_data\api.xml", System.AppDomain.CurrentDomain.BaseDirectory);
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;
}
}

What is the problem you can comment below, I do not have the technology in place, write bad hope everyone forgive me.

ASP. Webapi using swagger to generate test documents

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.