ASP. NET Web API tutorial 2.4 Creating a Help page for the Web API

Source: Internet
Author: User
Tags jquery accordion

Reference page:

Http://www.yuanjiaocheng.net/CSharp/csharprumenshili.html

Http://www.yuanjiaocheng.net/entity/mode-first.html

Http://www.yuanjiaocheng.net/entity/database-first.html

Http://www.yuanjiaocheng.net/entity/choose-development-approach.html

Http://www.yuanjiaocheng.net/entity/query-with-edm.html

Note: This article is part of the ASP. NET Web API Series tutorial, if you are looking at this blog post for the first time, please look at the previous content first.

2.4 Creating a help Page for a Web API
2.4 Creating the Web API help page

This article quoted: HTTP://WWW.ASP.NET/WEB-API/OVERVIEW/CREATING-WEB-APIS/CREATING-A-HELP-PAGE-FOR-A-WEB-API

by Mike Wasson | August 3, 2012
Mike Wasson | date: 2012-8-3

This tutorial shows how to create a help page for a Web API, by using the Apiexplorer class.
This tutorial shows how to use the Apiexplorer class to create a help page for the Web API.

The Apiexplorer class provides descriptive information about the APIs exposed by a Web API. Apiexplorer provides the raw material that's can use to create a help page. The apiexplorer contains an apidescription collection, one for each API that it discovers in your PROJEC T. For this purpose, a "API" is defined as the combination of HTTP method and relative URI. For example, here is some distinct APIs:
The Apiexplorer class provides descriptive information for each API exposed by the Web API. Apiexplorer provides the raw material that can be used to create help pages. Apiexplorer contains a collection of apidescription , a collection of each API found in your project. For this reason, the definition of an "API" is a combination of an HTTP method and a related URI. For example, here are a few different APIs:

    • Get/api/products (HTTP method is Get,uri is/api/products, the combination of the two is an API. Hereinafter-Translator Note)
    • Get/api/products/{id}
    • Post/api/products

If a single controller action supports multiple HTTP methods, the Apiexplorer treats each as a distinct API.
If a single controller action supports multiple HTTP methods,apiexplorer will treat each as a different API.

For this tutorial, we'll create the help page as a MVC view, using Razor syntax to render the HTML. First, create a new project using the "Web API" project template.
For this tutorial, we will create an MVC view of the help page and render the HTML using the Razor syntax. Start by creating a new project (2-27) with the Web API project template.

Figure 2-27. Create a project

This template creates a project, contains a WEB API controller (ValuesController.cs) and an MVC controller (Homecontro Ller.cs).
This template creates a project that contains a Web API controller (ValuesController.cs) and an MVC controller (HomeController.cs).

ADD a model class:
Add a model class:

namespace Helpdemo.models {public     class Product     {public         string Name {get; set;}         Public decimal price {get; set;}     } }

ADD another WEB API controller:
Add another Web API controller:

Namespace Helpdemo.controllers {     using System.Collections.Generic;     Using System.Net;     Using System.Net.Http;     Using System.Web.Http;     Using Helpdemo.models;     public class Productscontroller:apicontroller     {public         ienumerable<product> Get ()         {             return new product[0];         }         Public httpresponsemessage Get (int id)         {             return request.createresponse (Httpstatuscode.notfound);         }         public void Post (product value) {} public         void Put (int id, product value) {}}     }

This controller isn't really functional, and you don't have the to use this exact code. This purpose of this controller are just to give the apiexplorer something to consume.
This controller is not really functional, and you don't have to use the code exactly. The purpose of this controller is simply to provide apiexplorer with something to use. (It is intended to indicate that in a real application, a controller similar to this may be required, but its content (code) is subject to the discretion of the translator)

Next, we ll create a view model that gets the data from the apiexplorer. We could pass the apiexplorer object directly to the MVC view. However, encapsulating the apiexplorer in a model gives us more flexibility to manipulate the data.
Next, we'll create a view model that gets the data from Apiexplorer , and then pass the apiexplorer object directly to the MVC view. However, encapsulating the apiexplorer in a model allows us to maintain the data more flexibly.

 namespace Helpdemo.models {using System;     Using System.Collections.Generic;     Using System.Linq;     Using System.Web.Http.Controllers;     Using System.Web.Http.Description;         public class Apimodel {Iapiexplorer _explorer;  Public Apimodel (Iapiexplorer Explorer) {if (explorer = = null) {throw new             ArgumentNullException ("explorer");         } _explorer = Explorer; } public ilookup<string, Apidescription> Getapis () {return _explorer. Apidescriptions.tolookup (API = + API.         ActionDescriptor.ControllerDescriptor.ControllerName); }     } }

The Getapis method converts the collection into a ilookup, grouped by controller name. That's makes it easy to group, the help page by controller.
The Getapis method transforms a collection into a ilookup that is grouped by controller name. This makes it easy to group help pages by controller.

Open the source file for the MVC controller, HomeController.cs. Add an action to render the help page:
Open the MVC controller source file HomeController.cs. To add an action to render a help page:

Public ActionResult Help () {     var explorer = GlobalConfiguration.Configuration.Services.GetApiExplorer ();     Return View (New Apimodel (explorer)); }

Add A view for the Help action:
Add a view for this help action:

 @model HelpDemo.Models.ApiModel @{viewbag.title = "API help";} @section Scripts {@Scripts. Render ("~/bundle        S/jqueryui ") <script type=" Text/javascript ">//Apply jQuery accordion widget.         Use the collapsible part of jquery $ (function () {$ (". Accordion"). accordion ();}); </script>} <div id= "Body" class= "Content-wrapper" > 

If you run the application and navigate to/home/help, it should look similar to the following:
If you run this application and navigate to/home/help, the page looks similar (see figure 2-28):

Figure 2-28. help Page appearance

Adding a documentation Provider
Add a document Provider

You can provide documentation for your APIs by implementing the Idocumentationprovider interface. Documentation strings can come from any source. For this example, we'll define custom attributes that can is applied to the controller. The documentation provider would grab documentation strings from the attributes.
By implementing the Idocumentationprovider interface, you can provide documentation for the API. A document string (a string used as the content of a document-the translator's note) can be any resource you like (these resources are of course something about an API, such as a description of the API's role or meaning, what parameters, the types of these parameters and their effects, etc.-the translator's note). For this example, we will define some custom annotation properties that can be applied to the controller. The document provider captures the document string based on these annotation properties (gets information about the API based on the annotation properties and feeds the content into the document string for display in the help page-the translator's note).

For another approach, see Yao Huang Lin's blog post generating a Web API help page using Apiexplorer. He shows a documentation provider that pulls from XML documentation comments.
Another way to see Yao Huang Lin's blog post is "Generating a Web API help page using Apiexplorer (Generate a Web API with Apiexplorer)". He demonstrated a document provider that was collected from XML document annotations.

Here is the custom attributes:
The following are the custom annotation properties:

[AttributeUsage (AttributeTargets.Method)] public class Apidocattribute:attribute {public     Apidocattribute ( String doc)     {         documentation = DOC;     }     public string Documentation {get; set;}} [AttributeUsage (AttributeTargets.Method)] public class Apiparameterdocattribute:attribute {public     Apiparameterdocattribute (string param, string doc)     {         Parameter = param;         documentation = DOC;     }     public string Parameter {get; set;}     public string Documentation {get; set;}}

Here are a controller method with the attributes:
The following is a controller method that uses these annotation properties:

[Apidoc ("Gets a product by ID.")] [Apiparameterdoc ("id", "The ID of the product.")] Public httpresponsemessage Get (int id) {     //...}

Now add a class that implements Idocumentationprovider.
Now, add a class that implements Idocumentationprovider :

 public class Docprovider:idocumentationprovider {public string getdocumentation (Httpparameterdescriptor parame         Terdescriptor) {String doc = ""; var attr = Parameterdescriptor.actiondescriptor. Getcustomattributes<apiparameterdocattribute> (). Where (p = = P.parameter = = parameterdescriptor.parametername).         FirstOrDefault (); if (attr! = null) {doc = attr.         documentation;     } return doc;         public string getdocumentation (Httpactiondescriptor actiondescriptor) {string doc = ""; var attr = actiondescriptor.getcustomattributes<apidocattribute> ().         FirstOrDefault (); if (attr! = null) {doc = attr.         documentation;     } return doc; } }

Open the Global.asax.cs file and add the following code to the Application_Start method:
Open the Global.asax.cs file, and add the following code to the Application_Start method:

GlobalConfiguration.Configuration.Services.Replace (    typeof (Idocumentationprovider), New Docprovider ());

Apiexplorer automatically calls into the Idocumentationprovider interface to get documentation strings For each API. It stores them in the documentation property of the apidescription and apiparameterdescription Objects. The MVC view can access them as follows:
Apiexplorer automatically calls the Idocumentationprovider interface to get the document string for each API. Store them in the documentation property of the apidescription and apiparameterdescription objects. MVC accesses them in the following way, depending on the image:

@foreach (Var api in Group) {     

Now if you render the view, it shows the documentation strings:
Now, when the view is rendered, the document string is displayed (see Figure 2-29):

Figure 2-29. Help page showing the document string

Providing Sample Response bodies
Provides an example response body

One thing that's missing from our help page is examples of the HTTP response body. The Apiexplorer class does not provide any direct support for this. However, it does give the return type for each action. If the action returns a POCO, we can use this information to create a example response body, as follows:
One of the missing items from the help page above is an example of the HTTP response body. The Apiexplorer class does not provide any direct support for this. However, it can provide you with a return type for each action. If the action returns a Poco, we can use this information to create an example response body with the following steps:

      1.
    1. Look up an example instance of the POCO.
      Find an instance of Poco example.
    2. 2.
    3. Use a Media-type formatter to serialize the example instance.
      Use a media type formatter to serialize this example instance.
    4. 3.
    5. Display the result as a string.
      Displays the result as a string.

To see how this can work, add the following code to the Apimodel class:
To understand how to do this, add the following code to the Apimodel class:

Example instances//Example static product[] _products = new product[] {new Product () {Name = "Gizmo", Price = 1.05M }, New Product () {Name = "Gizmo2", Price = 0.995M}}; look-up table based on data type. Query table Dictionary<type based on data type, object> _sampledata = new Dictionary<type, object> () {{typeof (Product), _PR Oducts[0]}, {typeof (Ienumerable<product>), _products}}; Type Getresponsetype (Httpactiondescriptor action) {return action. ReturnType;     public string Getsampleresponsebody (Apidescription API, String mediatype) {string BODY = null; Type returntype = Getresponsetype (API.     Actiondescriptor);     Object o; if (returntype! = null && _sampledata.trygetvalue (returntype, out O)) {var formatters = API.         Supportedresponseformatters; Mediatypeformatter formatter = formatters.         FirstOrDefault (f = f.supportedmediatypes.any (M = M.mediatype = = mediatype));     if (formatter! = NULL)    {var content = new Objectcontent (ReturnType, O, formatter); BODY = content. Readasstringasync ().         Result; }} return body; }

ADD the following code to the MVC view:
Add the following code to the MVC view:

    @{          String response = @Model. Getsampleresponsebody (API, "Application/json");     }     @if (response! = null) {         <p>sample response body:</p>         <p><code>@ Model.getsampleresponsebody (API, "Application/json") </code></p>     }

Here are the resulting help page:
The following is the result of the help page (see Figure 2-30):

Figure 2-30. The help page for the example is displayed

This approach was not perfect. If an action returns a httpresponsemessage, there is no-deduce the format of the message body from the St atic API description. The same is true for a action that returns Loosely-structure JSON (see Anonymous and weakly-typed Objects).
This approach is not perfect. If an action returns Httpresponsemessage, there is no way to infer the format of the message body based on the static API description. Similarly, the action of returning the loosely structured JSON is the same (see Anonymous and weakly-typed Objects (anonymous and weakly typed objects)-6th chapter of this tutorial series).

The one-to-work around-problem is-to-use the API-ID to-look-up the response type. The API ID is a concatenation of the HTTP method and the relative URI path (for example, "Getapi/products/{id}").
One way to solve this problem is to use the API ID to find the response body type. The API ID is a concatenation of the HTTP method with the relative URI path (for example, "Getapi/products/{id}").

Response Types//Response type static dictionary<string, type> _responsetypes = new dictionary<string, type> ()     {         {@ "Getapi/products/{id}", typeof (Product)}     }; Type Getresponsetype (Apidescription API) {     type T;     if (_responsetypes.trygetvalue (api.id, Out T))     {         return t;     }     Return API. Actiondescriptor.returntype; }

Custom attributes is another option.
Custom annotation properties are another option (for this issue).

Excluding an API
Exclude an API

To hide a API from the apiexplorer, add the apiexplorersettings attribute to the action and set IGN Oreapi to True.
In order to hide an API from apiexplorer , add the apiexplorersettings annotation attribute to the action and set Ignoreapi to true:

[Apiexplorersettings (Ignoreapi=true)] public httpresponsemessage Get (int id) {}

You can also add this attribute to the controller and to exclude the entire controller.
You can also add this annotation attribute to the controller to exclude the entire controller (all APIs).

Read this article if you feel something rewarding, please give a recommendation

ASP. NET Web API tutorial 2.4 Creating a Help page for the Web API

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.