1. 首先创建一个 web 项目, 选择 Mvc 模板
2. 右键点击引用. 管理 Nuget 程序包, 浏览 搜索 Swagger, 下载安装下面的包
3. 安装完后在 App_Start 里面会出现 SwaggerConfig.cs 类, 并将 SwaggerConfig 类中的内容替换成下内容
- using System.Web.Http;
- using WebActivatorEx;
- using UseSwagger;
- using Swashbuckle.Application;
- using System;
- [assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")]
- namespace UseSwagger
- {
- public class SwaggerConfig
- {
- public static void Register()
- {
- var thisAssembly = typeof(SwaggerConfig).Assembly;
- GlobalConfiguration.Configuration
- .EnableSwagger(c =>
- {
- c.SingleApiVersion("v1", "WebApp");
- })
- .EnableSwaggerUi(c =>
- {
- GetXmlCommentsPath();
- });
- }
- private static string GetXmlCommentsPath()
- {
- return string.Format(@"{0}\bin\UseSwagger.XML", AppDomain.CurrentDomain.BaseDirectory);
- }
- }
- }
4. 在 App_Start 文件夹中创建一个 WebApiConfig.cs 内容为
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Http;
- namespace UseSwagger.App_Start
- {
- public class WebApiConfig
- {
- public static void Register(HttpConfiguration config)
- {
- // Web API 配置和服务
- // Web API 路由
- config.MapHttpAttributeRoutes();
- config.Routes.MapHttpRoute(
- name: "DefaultApi",
- routeTemplate: "api/{controller}/{action}/{id}",
- defaults: new
- {
- id = RouteParameter.Optional
- }
- );
- }
- }
- }
此时会发现 config.MapHttpAttributeRoutes(); 飘红报错. 此时需在引用 Microsoft.AspNet.WebApi.WebHost 包. 然后就不报错了.
5. 在 Global.asax 调用刚才添加的类的 Register 方法.
6. 右键项目 -> 属性 -> 生成 -> 勾上 xml 文档文件
然后继续点击 Web, 设置默认打开页面 (此处若不设置默认打开页面. 运行项目将会报错 404, 因为项目运行之后的地址不对. 正确的地址是 项目地址 / swagger/ui/index)
7. 创建一个 Controller, 然后继承 ApiController, 记得添加引用 using System.Web.Http;(若不继承自 ApiController 则不会再 Swagger 页面中显示)
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Http;
- using System.Web.Mvc;
- namespace UseSwagger.Controllers
- {
- public class TestController : ApiController
- {
- // GET: Test
- public int Index(int a)
- {
- return 0;
- }
- }
- }
至此 Swagger 已经可以使用了
来源: http://www.bubuko.com/infodetail-3096816.html