ASP. NET WEB API 2 Interface API documentation beautification of the swagger

Source: Internet
Author: User
Tags response code hosting



Using the Swgger UI provided by a third party effectively improves the readability of the Web API interface list and can test the service interface on the page.



But after I consulted a lot of data and coded the test, I found that most of the swagger instances did not run efficiently. For example, the following two URLs: Http://www.cnblogs.com/caodaiming/p/4156476.html and http://bitoftech.net/2014/08/25/ asp-net-web-api-documentation-using-swagger/. After my some toss, finally found that the original version of the difference caused by the (above two examples in the 4.2.0 version of the successful operation, the reader can self-test). Well, if these authors can mark the version of the plugin package, it can really save a lot of effort.



The latest stable version of Swashbuckle is now in version 5.2.1 . This version is encoded in a way that differs from the 4.2.0 version, as illustrated in the 5.2.1 version.



Note: This article uses Owin from the Homestay (self-host) Web API, which is unclear for readers to refer to: http://www.asp.net/web-api/overview/hosting-aspnet-web-api/ Use-owin-to-self-host-web-api.



1. Create a new console application Owinconsoleapp. NuGet adds Swashbuckle (5.2.1 version) and Microsoft.AspNet.WebApi.OwinSelfHost respectively. When you add Swashbuckle, the App_start folder and a file named "Swaggerconfig" are automatically added to the project.



2. Create a new Studentcontroller file with the following code:




using System;
using System.Collections.Generic;
using System.Web.Http;
using System.Web.Http.Description;
namespace OwinConsoleApp
{
    /// <summary>
    /// student information
    /// </ summary>
    public class StudentController: ApiController
    {
        /// <summary>
        /// get all student information
        /// </ summary>
        /// <returns> </ returns>
        public IEnumerable <string> Get ()
        {
            return new List <string> () {"student A", "student B"};
        }
        /// <summary>
        /// get student information based on student number
        /// </ summary>
        /// <param name = "Id"> Student ID </ param>
        /// <returns> </ returns>
        public string Get (int Id)
        {
            return "Student ID:" + Id;
        }
        /// <summary>
        /// add students
        /// </ summary>
        /// <param name = "studentModel"> student entity </ param>
        /// <remarks> Add a new student </ remarks>
        /// <response code = "400"> Bad request </ response>
        /// <response code = "500"> Internal Server Error </ response>
        public void Post (String studentModel)
        {
        }
        /// <summary>
        /// modify student information
        /// </ summary>
        /// <param name = "Id"> Student ID </ param>
        /// <param name = "studentModel"> student entity </ param>
        [ResponseType (typeof (string))]
        [ActionName ("UpdateStudentById")]
        public void Put (int Id, string studentModel)
        {
        }
        /// <summary>
        /// delete student information
        /// </ summary>
        /// <param name = "Id"> Student ID </ param>
        public void Delete (int Id)
        {
        }
    }
}





3. Modify the Swaggerconfig file as follows:




using System.Linq;
using System.Web.Http;
using WebActivatorEx;
using OwinConsoleApp;
using Swashbuckle.Application;
[assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")]
namespace OwinConsoleApp
{
    public class SwaggerConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.EnableSwagger(c =>
                    {
                        c.SingleApiVersion("v1", "");
                        c.IncludeXmlComments(GetXmlCommentsPath());
                        c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
                    })
                .EnableSwaggerUi();
        }
        private static string GetXmlCommentsPath()
        {
            return System.String.Format(@"{0}\Swagger.XML", System.AppDomain.CurrentDomain.BaseDirectory);
        }
    }
}
4. Create a new startup file with the following code:






using Owin;
using Microsoft.Owin;
using System.Web.Http;
using Swashbuckle.Application;
[assembly: OwinStartup(typeof(OwinConsoleApp.Startup))]
namespace OwinConsoleApp
{
    public class Startup
    {
        public void Configuration(IAppBuilder appBuilder)
        {
            // Configure Web API for self-host. 
            HttpConfiguration config = new HttpConfiguration();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            SwaggerConfig.Register(config);
            appBuilder.UseWebApi(config);
        }
    }
}
5, modify program programs, the code is as follows:






using System;
using Microsoft.Owin.Hosting;
namespace OwinConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string baseAddress = "http://localhost:9000/";
            // Start OWIN host 
            using (WebApp.Start<Startup>(url: baseAddress))
            {
                Console.WriteLine("OWIN SERVICE OPEN!");
                Console.Read();
            }
            Console.ReadLine();
        }
    }
}


6. Right -click Project properties to set the output document in the properties ' build ':






Note: The XML file path and file name here should be consistent with the configuration in the Swaggerconfig file.





7, the administrator to run the program. Enter the following address in the browser: Http://localhost:9000/swagger, the following page is displayed:







Click the appropriate service, enter the corresponding information in the box that appears, and then click "Try it out! , the service can be invoked successfully, and the returned results are viewable.



Something: After two days, finally put swagger out of the original is in the version of the difference wasted too much time. Write this article and share it with people who have the same experience as me. If there are any flaws in the text, please also point out.














Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.



ASP. NET WEB API 2 Interface API documentation beautification of the swagger


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.