C#------如何使用Swagger除錯介面
阿新 • • 發佈:2018-11-01
轉自:https://www.cnblogs.com/tianhengblogs/p/7290152.html
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 [email protected]"{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/
結果展示: