
一、Swagger配置
1、注解不显示
SwaggerConfig文件下
//c.IncludeXmlComments(GetXmlCommentsPath()); 内下面添加:
c.IncludeXmlComments(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, @"bin\YDShengya_WebApi.xml"));
然后报错
未能找到输出的XML文件 -我去bin目录也没有找到
具体解决方案:
原本调试环境下配置的
在发布配置下Release 也配置输出生成XML才ok
保存即可发布-包含XML的文件
注意:运行时提示
请将注册表值 [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD)设置为 1
则 即可。
2、使用Swagger 让某些接口不显示在文档
在Action 上加[ApiExplorerSettings(IgnoreApi = true)]
[HttpGet]
[ApiExplorerSettings(IgnoreApi = true)]
public ActionResult Index(string appKey , string username )
{
//todo
}
3、Swagger默认路由
Core是在StartUp.cs文件配置
基于framework 配置swagger
指定 route rule 使用Swashbuckle.Application.RedirectHandler,实现原理----route template 完全沒有 request 參數時導向 \swagger。
- 想了解如何轉導,請參考 RedirectHandler.cs
routes.MapHttpRoute(
name: "swagger_root",
routeTemplate: "",
defaults: null,
constraints: null,
handler: new Swashbuckle.Application.RedirectHandler((message => message.RequestUri.ToString()), "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作为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