NET Webapi, using swagger

Source: Internet
Author: User

NET Webapi, using swagger

When I use swagger in the WEBAPI, I find that there will be many problems, search many places did not find a complete solution to the problem, after their own solution, I hope to meet the same problem friends have help. I'll start with a step-by-step demonstration project to solve swagger problems and workarounds.

First we create a new API project

Figure 1 (default build project)

Figure 2 (run home)

Figure 3 (Default API list)

Figure 4 (API for default get)

The page that is generated by default at 1-4 is not so good looking, and the test is inconvenient, here's how to use swagger.

Use the NuGet package to get swashbule, swagger packages and install them.

Figure 5 (Swashbule-swagger for API)

Figure 6 (Swagger UI for net)

General installation should be able to run normally. But after running we find that throwing an exception

Figure 7 (Exception 1)

Open the solution Properties-Generate, tick the XML document file, save on OK.

Figure 8

Figure 9 (Exception 2)

This exception occurs because no dependencies are added, and you can view your DLL file versions yourself, make changes, and insert the following code into the Web. config.

123456789101112 <dependentAssembly>    <assemblyIdentity name="System.Net.Http.Formatting"publicKeyToken="31bf3856ad364e35"culture="neutral"/>    <bindingRedirect oldVersion="0.0.0.0-5.0.0.0"newVersion="5.0.0.0"/>  </dependentAssembly>  <dependentAssembly>    <assemblyIdentity name="System.Web.Http"publicKeyToken="31bf3856ad364e35" culture="neutral"/>    <bindingRedirect oldVersion="0.0.0.0-5.0.0.0"newVersion="5.0.0.0"/>  </dependentAssembly>  <dependentAssembly>    <assemblyIdentity name="Newtonsoft.Json"publicKeyToken="30ad4fe6b2a6aeed"culture="neutral"/>    <bindingRedirect oldVersion="0.0.0.0-8.0.0.0"newVersion="8.0.0.0"/>  </dependentAssembly>

Commenting on two lines of code in Swagger.net, it is estimated that the code in the NuGet package has not been updated to cause this exception to appear

Figure 10 (note does not require code)

Okay, now let's look at the effects that can be run, and entering Url:http://localhost:28129/swagger in the browser will automatically jump to Http://localhost:28129/swagger/ui/index

Figure 11

At this point we are able to run the swagger very convenient debugging interface.

To facilitate testing, we created a new app model

    <summary>/    //app info/    //</summary> public class app    {        //<summary>// //App ID number///        </summary> public        int ID {get; set;}        <summary>////        The name of the app///        </summary> public        string name {get; set;}        <summary>////App description///        </summary> public        string Remark {get; set;}    }

Returns the model of the message Resultjson

    <summary>///    return processing results///    </summary> public    class Resultjson {//        <summary >///Return code///        </summary> public        int code {get; set;}        <summary>///return message///        </summary> public        string Message {get; set;}    }

Add a new API for AppController

 public class Appcontroller:apicontroller {private list<app> Getapps () {list<app& Gt            List = new list<app> (); List.            ADD (New App () {Id = 1, Name = "WeChat", Remark = "WeChat"}); List.            ADD (New App () {Id = 2, Name = "Facebook", Remark = "Facebook"}); List.            ADD (New App () {Id = 3, Name = "Google", Remark = "Google"}); List.            ADD (New App () {Id = 4, Name = "QQ", Remark = "QQ"});        return list; }///<summary>//Get all apps//</summary>//<returns> all app collections </returns&        Gt        [HttpGet] public httpresponsemessage Get () {return Myjson.objecttojson (Getapps ()); }///<summary>//Get the specified app///</summary>//<param name= "id" > Need to get app ID&L t;/param>//<returns> returns the specified app</returns> [httpget] public httpresponsemessage Get (int     Id   {var app = Getapps (). Where (M = m.id.equals (Id)).            FirstOrDefault ();        Return Myjson.objecttojson (APP); }///<summary>//Add app information///</summary>//<param name= "value" ></para m>//<returns></returns> [HttpPost] public httpresponsemessage Insert ([Frombody]app            Value) {Resultjson json = new Resultjson () {Code = $, Message = "OK"};        Return Myjson.objecttojson (JSON); }///<summary>//Update app information///</summary>//<param name= "value" >app Information < /param>//<returns> update results </returns> [httpput] public httpresponsemessage updateapp ([Fr            Ombody]app value) {Resultjson json = new Resultjson () {Code = $, Message = "OK"};        Return Myjson.objecttojson (JSON); }//<summary>///Delete app information///&LT;/SUMMARY&GT <param name= "id" >app number </param>///<returns> Delete result </returns> [Httpdelete] P  Ublic httpresponsemessage deleteapp (int id) {Resultjson json = new Resultjson () {Code = $, Message =            "OK"};        Return Myjson.objecttojson (JSON); }    }

In order to satisfy the need to use the JSON format data, proposed a class

    public class Myjson    {public        static httpresponsemessage Objecttojson (object obj)        {            JavaScriptSerializer js = new JavaScriptSerializer ();            String r = js. Serialize (obj);            var result = new Httpresponsemessage (Httpstatuscode.ok)            {                Content = new Stringcontent (R, Encoding.UTF8, "text/ JSON ")            };            return result;        }        public static Httpresponsemessage Objecttojson (list<object> objs)        {            JavaScriptSerializer js = new JavaScriptSerializer ();            String r = js. Serialize (OBJS);            var result = new Httpresponsemessage (Httpstatuscode.ok)            {                Content = new Stringcontent (R, Encoding.UTF8, "text /json ")            };            return result;        }    }

Okay, we can see the effect after we run it.

Figure 12

Click Try it out

Figure 13

We can also open the note, we can see the comments in the page, easy to debug the interface when the caller understand the parameters of the information. Open it

public class swaggerconfig{public    static void Register () {            var thisassembly = typeof (Swaggerconfig). Assembly;            Globalconfiguration.configuration                 . Enableswagger (c + =                    {                        c.singleapiversion ("v1", "Swaggerapidemo");                        C.includexmlcomments (Getxmlcommentspath ());                    })                . Enableswaggerui (c + =                    {                                });        }                private static string Getxmlcommentspath ()        {            return string. Format ("{0}/bin/swaggerapidemo.xml", System.AppDomain.CurrentDomain.BaseDirectory);}        }

The above marker color is new additions, so let's look at the final effect.

Figure 14

Figure 15

We can see the comment section so that our swagger is done.

I send the final code here, there is a need for code when friends can download directly.

Http://pan.baidu.com/s/1mhFVZ4W

Tags: swagger, webapi, C #

NET Webapi, using swagger

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.