C#------如何使用Swagger调试接口
1.打开NuGet程序包
2.安装下面两个程序包
3.安装完后会出现SwaggerConfig.cs类,并修改里面的内容
代码:
[assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")] namespace WebApplication1 { 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 $@"{System.AppDomain.CurrentDomain.BaseDirectory}\bin\WebApi.XML"; } }
4.添加WebApi.cs类
代码:
namespace WebApi { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi1", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Routes.MapHttpRoute( name: "DefaultApi2", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { action="get",id = RouteParameter.Optional } ); } } }
5.修改Global.asax类
代码:
public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); GlobalConfiguration.Configure(WebApiConfig.Register); //这是要加的 } }
6.设置需要调试的类
7.设置生成的XML文档
8.运行项目,打开浏览器输入http://localhost:23092/swagger/
结果展示: