WebApi Swagger使用

参考地址:
http://blog.csdn.net/yuchen_0515/article/details/51762958
http://www.dakehe.info/blog/post/how-to-use-swagger-at-aspnet-mvc

Install-Package Swashbuckle
github网址:https://github.com/domaindrivendev/Swashbuckle

更改点:


image.png

swagger的xml路径根据项目来
App_Start目录下的SwaggerConfig.cs

using System.Linq;

public static void Register()  
       {  
           var thisAssembly = typeof(SwaggerConfig).Assembly;  
           GlobalConfiguration.Configuration  
               .EnableSwagger(c =>  
                   {  
  
                       c.SingleApiVersion("v1", "API Test");  
                       c.IncludeXmlComments(GetXmlCommentsPath());  
                       c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());  
                   })  
               .EnableSwaggerUi(c =>  
                   {  
  
                   });  
       } 

private static string GetXmlCommentsPath()
        {
            return System.AppDomain.CurrentDomain.BaseDirectory + @"\bin\WebApiSwagger.XML";
        }

项目结构:


image.png
namespace WebApiSwagger.Controllers.Api
{
    /// 
    /// 产品API接口
    /// 
    public class ProductsController : ApiController
    {
        Product[] products = new Product[] 
        { 
            new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 }, 
            new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M }, 
            new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M } 
        };

        /// 
        /// 获取所有的产品
        /// 
        /// 所有产品
        public IEnumerable GetAllProducts()
        {
            return products;
        }

        /// 
        /// 根据Id获取产品
        /// 
        /// 产品Id
        /// 产品信息
        public IHttpActionResult GetProduct(int id)
        {
            var product = products.FirstOrDefault((p) => p.Id == id);
            if (product == null)
            {
                return NotFound();
            }
            return Ok(product);
        }
    }
}

Homt/Index.cshtml

@{
    Layout = null;
    ViewBag.Title = "Home Page";
}




    Product App


    
@Html.ActionLink("Swagger Help", "", "Swagger", new { area = "" }, null)

All Products

Search by ID

上面的 导航到接口页

@Html.ActionLink("Swagger Help", "", "Swagger", new { area = "" }, null)
image.png

Web.config中允许跨域设置 在system.webServer节点下增加如下配置


      
      
        
        
        
        
      
    

你可能感兴趣的:(WebApi Swagger使用)