Joke Collection Website - News headlines - How to make WebAPI automatically generate beautiful and practical online API documents

How to make WebAPI automatically generate beautiful and practical online API documents

1. 1 SwaggerUI

SwaggerUI is a simple Restful API testing and documentation tool. Simple, beautiful and easy to use (official demonstration). Display API by reading JSON configuration. The project itself only depends on some static html, css.js files. You can use it on almost any Web container.

1.2 Cross buckle

Swashbuckle is a. NET class library, which can generate JSON configuration corresponding to SwaggerUI from all open controller methods of WebAPI. And then show it through SwaggerUI. The class library already contains SwaggerUI. No additional installation is required.

Quick start

Create a project OnlineAPI to package Baidu music service (sample download), through which you can search, get music information and play links.

I tried to delete some files that we won't use in the presentation to make them look simpler.

WebAPI installation Swashbuckle

Installation package Swashbuckle

Code comments generate document descriptions.

Swashbuckle reads comments through the generated XML file and generates descriptions in SwaggerUI and JSON configuration.

During the installation process, a SwaggerConfig.cs configuration file will be generated under the project directory App_Start folder, which is used to configure the relevant display behavior of SwaggerUI. As shown in the figure:

Delete about 99 lines of comments from the configuration file and modify it to

c.include XML comments(GetXmlCommentsPath(this assembly。 GetName()。 Name));

And add the method to the current class.

///& lt; Summary & gt

///& lt; /summary & gt;

///& lt; param name = " name " & gt& lt/param & gt;

///& lt; returns & gt& lt/returns & gt;

Protected static string GetXmlCommentsPath (string name)

{

Returns a string. Format (@"{0}\bin\{ 1}. XML”,AppDomain。 CurrentDomain.BaseDirectory,name);

}

Then check "XML document file" in this Web project attribute generation tab to generate the annotation file of the class library at compile time.

Add 3 APIs of Baidu Music

Please visit http://

We test whether the API runs successfully through the API.

3. Add a custom HTTP header

Authentication authority is often needed when developing mobile API, and it is best to put authentication parameters in the Http request header. WebAPI works with filters to verify permissions.

First, we need to create a class of IOperationFilter interface. IOperationFilter

Use the system;

Use the system. Assemble. Generics;

Use the system. Linq

Use the system. Web

Use the system. Web . Http

Use the system. Web . Http.Description

Use the system. Web page filter;

Use Swashbuckle. Swindle through the city;

Namespace OnlineAPI effectiveness

{

Public class httpheaderfilter: ioperationfilter

{

Public void application (Operation, SchemaRegistry

schemaRegistry,ApiDescription apiDescription)

{

if(operation . parameters = = null)operation . parameters = new

List & lt parameter & gt ();

Var filter pipe =

API description. action descriptor . GetFilterPipeline();

//Judge whether to add a permission filter.

var isAuthorized = filterPipeline。 Select (filterInfo =>

filterInfo。 Example). any(filter = & gt; Filter is iauthorizationfilter);

//Determines whether anonymous methods are allowed.

var allowAnonymous =

API description. action descriptor . GetCustomAttributes & lt; AllowAnonymousAttribute & gt().any();

if(is authorized & amp; & amp! allowAnonymous)

{

Operation.parameters.Add (new parameter

{

name = "access-key ",

@in = "header ",

Description = "User Access Key",

Required = false,

type = "string "

});

}

}

}

}

Add a line of registration code to the anonymous method class of EnableSwagger configuration in SwaggerConfig.cs

c.OperationFilter & ltHttpHeaderFilter & gt();

Add a Web rights filter

Use the system;

Use the system. Assemble. Generics;

Use the system. Linq

Use System.Net;

Use the system. Net . Http

Use the system. Text;

Use the system. Web

Use the system. Web . Http

Use the system. Controller;

Use Newtonsoft. Json

Namespace OnlineAPI effectiveness

{

///& lt; Summary & gt

///

///& lt; /summary & gt;

Public class accesskeyattribute: authorizeattribute

{

///& lt; Summary & gt

///Permission verification

///& lt; /summary & gt;

///& lt; param name = " actionContext " & gt& lt/param & gt;

///& lt; returns & gt& lt/returns & gt;

Protected alternative Boolean values are authorized (httpactioncontext).

{

Var request = actionContext. Request;

If (requested. Head. Contains ("access key"))

{

var accessKey = request。 Headers.GetValues("access-key ")。 SingleOrDefault();

//TODO authentication key

return access key = = " 123456789 ";

}

Returns false

}

///& lt; Summary & gt

///Handling unauthorized requests

///& lt; /summary & gt;

///& lt; param name = " actionContext " & gt& lt/param & gt;

Protected rewrite Void HandleUnauthorized Request (HttpacktionContext Action Context)

{

var content = JsonConvert。 serialize object(new { State = HttpStatusCode。 Unauthorized});

ActionContextResponse = new HttpResponseMessage

{

Content = new StringContent (content, encoding. UTF8, "Application /json"),

StatusCode = HttpStatusCode。 Unauthorized

};

}

}

}

Add a filter to the desired ApiController or operation.

[Access Key]

Final display effect

4. Display upload file parameters

SwaggerUI has the function of uploading files, which is similar to adding a custom HTTP header, except that we use special settings to indicate that the API has the function of uploading files.

Use the system;

Use the system. Assemble. Generics;

Use the system. Linq

Use the system. Web

Use the system. Web . Http.Description

Use Swashbuckle. Swindle through the city;

Namespace OnlineAPI effectiveness

{

///& lt; Summary & gt

///

///& lt; /summary & gt;

Public class UploadFilter: IOperationFilter

{

///& lt; Summary & gt

///File upload

///& lt; /summary & gt;

///& lt; param name = " operation " & gt& lt/param & gt;

///& lt; param name = " schemaRegistry " & gt& lt/param & gt;

///& lt; param name = " apiDescription " & gt& lt/param & gt;

public void Apply(Operation Operation,SchemaRegistry schemaRegistry,ApiDescription apiDescription)

{

If (! String. IsNullOrWhiteSpace(operation . summary)& amp; & ampoperation.summary.Contains ("upload"))

{

Operation.consumes.Add ("application/form-data");

Operation.parameters.Add (new parameter

{

Name = "file",

@in = "formData ",

Necessary = true,

Type = "file"

});

}

}

}

}

Add a line of registration code to the anonymous method class of EnableSwagger configuration in SwaggerConfig.cs

c.OperationFilter & ltUploadFilter & gt();

API document display effect