一、Swagger配置

时间:2023-03-09 13:26:44
一、Swagger配置

一、Swagger配置

1、注解不显示

SwaggerConfig文件下

  //c.IncludeXmlComments(GetXmlCommentsPath());  内下面添加:

c.IncludeXmlComments(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, @"bin\YDShengya_WebApi.xml"));

 一、Swagger配置 

然后报错一、Swagger配置

未能找到输出的XML文件 -我去bin目录也没有找到

具体解决方案:

原本调试环境下配置的

一、Swagger配置

在发布配置下Release 也配置输出生成XML才ok

一、Swagger配置

保存即可发布-包含XML的文件

注意:运行时提示

请将注册表值 [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD)设置为 1

一、Swagger配置  即可。

2、使用Swagger 让某些接口不显示在文档

在Action 上加[ApiExplorerSettings(IgnoreApi = true)]

[HttpGet]
[ApiExplorerSettings(IgnoreApi = true)]
public ActionResult Index(string appKey , string username )
{
//todo
}

  

3、Swagger默认路由

Core是在StartUp.cs文件配置

一、Swagger配置

基于framework 配置swagger

  指定 route rule 使用Swashbuckle.Application.RedirectHandler,实现原理----route template 完全沒有 request 參數時導向 \swagger。

routes.MapHttpRoute(
name: "swagger_root",
routeTemplate: "",
defaults: null,
constraints: null,
handler: new Swashbuckle.Application.RedirectHandler((message => message.RequestUri.ToString()), "swagger")
);

  一、Swagger配置

随机更改

config.Routes.MapHttpRoute(
name: "swagger_root",
routeTemplate: "",
defaults: null,
constraints: null,
handler: new Swashbuckle.Application.RedirectHandler((message => message.RequestUri.ToString()), "swagger/ui/index")
);

  一、Swagger配置

这里不做随意更改直接用Swagger作为root具体代码参考

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing; namespace YDShengya_WebApi
{
/// <summary>
/// 設定預設導向 Swashbuckle 頁面
/// </summary>
public class RouteConfig
{
/// <summary>
/// 在 RouteConfig 中加入一組 route rule 指定 route rule 使用 Swashbuckle.Application.RedirectHandler
/// </summary>
/// <param name="routes"></param>
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapHttpRoute(
name: "swagger_root",
routeTemplate: "",
defaults: null,
constraints: null,
handler: new Swashbuckle.Application.RedirectHandler((message => message.RequestUri.ToString()), "swagger")
); routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}

  参考博客

3、MVC和WebApi路由区别汇总

WebApi的默认路由机制通过http请求的类型匹配Action,MVC的默认路由机制通过url匹配Action
WebApi的路由配置文件是WebApiConfig.cs,MVC的路由配置文件是RouteConfig.cs
WebApi的Controller继承自Web.Http.ApiController,MVC的Controller继承自Web.Mvc.Controller