@目錄
- 1 安裝
- 2 修改名稱和版本號
- 3 顯示說明
- 4 顯示控制器注釋及漢化
- 5 路由相同,查詢引數不同的方法
- 6 忽略 Model 中的某些欄位
- 7 傳遞 header
- 8 出錯時的 HTTP 狀態碼
開發 web api 的時候,寫檔案是個痛苦的事情,而沒有檔案別人就不知道怎么呼叫,所以又不得不寫,
swagger 可以自動生成介面檔案,并測驗介面,極大的解放了程式員的生產力,
1 安裝
通過 NuGet 安裝 Swashbuckle,

安裝完成后,App_Start 檔案夾下會多出一個 SwaggerConfig.cs 檔案,

重新生成并發布 api,打開網頁 http://localhost:7001/swagger(這里注意換成你的 host)
網頁顯示如下:

2 修改名稱和版本號
上圖中框出的名稱和版本號是可以修改的,打開 SwaggerConfig.cs 檔案,找到如下代碼:
c.SingleApiVersion("v1", "API.Test");
修改其中的引數,重新發布即可,
3 顯示說明
swagger 可以讀取代碼中的注釋,并顯示在網頁上,如此一來,我們只需要在代碼中將注釋寫好,就可以生成一份可供他人閱讀的 API 檔案了,
swagger 是通過編譯時生成的 xml 檔案來讀取注釋的,這個 xml 檔案默認是不生成的,所以先要修改配置,
第一步: 右鍵專案 -> 屬性 -> 生成,把 XML 檔案檔案勾上,

第二步: 添加配置
在 SwaggerConfig.cs 檔案中添加配置如下:
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.SingleApiVersion("v2", "測驗 API 介面檔案");
// 配置 xml 檔案路徑
c.IncludeXmlComments($@"{System.AppDomain.CurrentDomain.BaseDirectory}\bin\API.Test.xml");
})
注意:發布的時候,XML 檔案不會一起發布,需要手動拷到發布目錄下,

4 顯示控制器注釋及漢化
默認是不會顯示控制器注釋的,需要自己寫,
在 App_Start 中新建類 SwaggerControllerDescProvider,代碼如下:
/// <summary>
/// swagger 顯示控制器的描述
/// </summary>
public class SwaggerCacheProvider : ISwaggerProvider
{
private readonly ISwaggerProvider _swaggerProvider;
private static ConcurrentDictionary<string, SwaggerDocument> _cache = new ConcurrentDictionary<string, SwaggerDocument>();
private readonly string _xmlPath;
/// <summary>
///
/// </summary>
/// <param name="swaggerProvider"></param>
/// <param name="xmlpath">xml檔案路徑</param>
public SwaggerCacheProvider(ISwaggerProvider swaggerProvider, string xmlpath)
{
_swaggerProvider = swaggerProvider;
_xmlPath = xmlpath;
}
public SwaggerDocument GetSwagger(string rootUrl, string apiVersion)
{
var cacheKey = string.Format("{0}_{1}", rootUrl, apiVersion);
//只讀取一次
if (!_cache.TryGetValue(cacheKey, out SwaggerDocument srcDoc))
{
srcDoc = _swaggerProvider.GetSwagger(rootUrl, apiVersion);
srcDoc.vendorExtensions = new Dictionary<string, object>
{
{ "ControllerDesc", GetControllerDesc() }
};
_cache.TryAdd(cacheKey, srcDoc);
}
return srcDoc;
}
/// <summary>
/// 從API檔案中讀取控制器描述
/// </summary>
/// <returns>所有控制器描述</returns>
public ConcurrentDictionary<string, string> GetControllerDesc()
{
ConcurrentDictionary<string, string> controllerDescDict = new ConcurrentDictionary<string, string>();
if (File.Exists(_xmlPath))
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(_xmlPath);
string[] arrPath;
int cCount = "Controller".Length;
foreach (XmlNode node in xmldoc.SelectNodes("//member"))
{
string type = node.Attributes["name"].Value;
if (type.StartsWith("T:"))
{
arrPath = type.Split('.');
string controllerName = arrPath[arrPath.Length - 1];
if (controllerName.EndsWith("Controller")) //控制器
{
//獲取控制器注釋
XmlNode summaryNode = node.SelectSingleNode("summary");
string key = controllerName.Remove(controllerName.Length - cCount, cCount);
if (summaryNode != null && !string.IsNullOrEmpty(summaryNode.InnerText) && !controllerDescDict.ContainsKey(key))
{
controllerDescDict.TryAdd(key, summaryNode.InnerText.Trim());
}
}
}
}
}
return controllerDescDict;
}
}
另外,新建 swagger.js 檔案并將其設定成 嵌入的資源,這個檔案的作用就是顯示控制器注釋及漢化,js 代碼如下:
'use strict';
window.SwaggerTranslator = {
_words: [],
translate: function () {
var $this = this;
$('[data-sw-translate]').each(function () {
$(this).html($this._tryTranslate($(this).html()));
$(this).val($this._tryTranslate($(this).val()));
$(this).attr('title', $this._tryTranslate($(this).attr('title')));
});
},
setControllerSummary: function () {
$.ajax({
type: "get",
async: true,
url: $("#input_baseUrl").val(),
dataType: "json",
success: function (data) {
var summaryDict = data.ControllerDesc;
var id, controllerName, strSummary;
$("#resources_container .resource").each(function (i, item) {
id = $(item).attr("id");
if (id) {
controllerName = id.substring(9);
strSummary = summaryDict[controllerName];
if (strSummary) {
$(item).children(".heading").children(".options").first().prepend('<li class="controller-summary" title="' + strSummary + '">' + strSummary + '</li>');
}
}
});
}
});
},
_tryTranslate: function (word) {
return this._words[$.trim(word)] !== undefined ? this._words[$.trim(word)] : word;
},
learn: function (wordsMap) {
this._words = wordsMap;
}
};
/* jshint quotmark: double */
window.SwaggerTranslator.learn({
"Warning: Deprecated": "警告:已過時",
"Implementation Notes": "實作備注",
"Response Class": "回應類",
"Status": "狀態",
"Parameters": "引數",
"Parameter": "引數",
"Value": "值",
"Description": "描述",
"Parameter Type": "引數型別",
"Data Type": "資料型別",
"Response Messages": "回應訊息",
"HTTP Status Code": "HTTP 狀態碼",
"Reason": "原因",
"Response Model": "回應模型",
"Request URL": "請求 URL",
"Response Body": "回應體",
"Response Code": "回應碼",
"Response Headers": "回應頭",
"Hide Response": "隱藏回應",
"Headers": "頭",
"Try it out!": "試一下!",
"Show/Hide": "顯示/隱藏",
"List Operations": "顯示操作",
"Expand Operations": "展開操作",
"Raw": "原始",
"can't parse JSON. Raw result": "無法決議 JSON,原始結果",
"Model Schema": "模型架構",
"Model": "模型",
"apply": "應用",
"Username": "用戶名",
"Password": "密碼",
"Terms of service": "服務條款",
"Created by": "創建者",
"See more at": "查看更多:",
"Contact the developer": "聯系開發者",
"api version": "api 版本",
"Response Content Type": "回應 Content Type",
"fetching resource": "正在獲取資源",
"fetching resource list": "正在獲取資源串列",
"Explore": "瀏覽",
"Show Swagger Petstore Example Apis": "顯示 Swagger Petstore 示例 Apis",
"Can't read from server. It may not have the appropriate access-control-origin settings.": "無法從服務器讀取,可能沒有正確設定 access-control-origin,",
"Please specify the protocol for": "請指定協議:",
"Can't read swagger JSON from": "無法讀取 swagger JSON于",
"Finished Loading Resource Information. Rendering Swagger UI": "已加載資源資訊,正在渲染 Swagger UI",
"Unable to read api": "無法讀取 api",
"from path": "從路徑",
"server returned": "服務器回傳"
});
$(function () {
window.SwaggerTranslator.translate();
window.SwaggerTranslator.setControllerSummary();
});
在 SwaggerConfig.cs 添加如下配置:
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.CustomProvider((defaultProvider) => new SwaggerCacheProvider(defaultProvider, $@"{System.AppDomain.CurrentDomain.BaseDirectory}\bin\API.Test.xml"));
})
.EnableSwaggerUi(c =>
{
c.InjectJavaScript(System.Reflection.Assembly.GetExecutingAssembly(), "API.Test.swagger.js");
});
5 路由相同,查詢引數不同的方法
在實際的 ASP.NET Web API 中,是可以存在 路由相同,HTTP 方法相同,查詢引數不同 的方法的,但不好意思,swagger 中不支持,并且會直接報錯,
如下代碼,
[Route("api/users")]
public IEnumerable<User> Get()
{
return users;
}
[Route("api/users")]
public IEnumerable<User> Get(int sex)
{
return users;
}
報錯: Multiple operations with path 'api/users' and method 'GET'.

可以在 SwaggerConfig.cs 添加如下配置:
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
})
此配置的意思是,當遇到此種情況時,取第一個方法展示,
這可以避免報錯,但多個方法只會在 swagger 中展示一個,治標不治本,不推薦,所以唯一的解決方案就是設定成不同的路由,不知道這個問題在之后的版本中會不會修復,
6 忽略 Model 中的某些欄位
如下圖,新建用戶時,后臺需要一個 User 類作為引數,點擊右側的 Model,可以顯示 User 類的屬性及注釋,

但是,有些欄位其實是無需呼叫者傳遞的,例如 State,呼叫者無需知道這些欄位的存在,
給這些屬性標記上 [Newtonsoft.Json.JsonIgnore] 特性,swagger 中不再顯示了,
當然這種做法也是有缺點的,因為 web api 在回傳資料時,呼叫的默認序列化方法也是 Newtonsoft.Json 序列化,
7 傳遞 header
呼叫 api 時,有些資訊是放在 HTTP Header 中的,例如 token,這個 swagger 也是支持的,
新建一個特性:
public class ApiAuthorizeAttribute : Attribute
{
}
新建一個類代碼如下:
public class AuthorityHttpHeaderFilter : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
if (operation.parameters == null)
operation.parameters = new List<Parameter>();
//判斷是否添加權限過濾器
var isAuthorized = apiDescription.ActionDescriptor.GetCustomAttributes<ApiAuthorizeAttribute>().Any();
if (isAuthorized)
{
operation.parameters.Add(new Parameter { name = "token", @in = "header", description = "令牌", required = false, type = "string" });
}
}
}
這段代碼就是告訴 swagger,如果遇到的方法上標記了 ApiAuthorizeAttribute 特性,則添加一個名為 token 的引數在 header 中,
最后需要在 SwaggerConfig.cs 中注冊這個過濾器,
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.OperationFilter<AuthorityHttpHeaderFilter>();
})
效果如下:

8 出錯時的 HTTP 狀態碼
我們在方法中回傳一個 400
[Route("api/users")]
public HttpResponseMessage Post([FromBody]User user)
{
return new HttpResponseMessage()
{
Content = new StringContent("新建用戶出錯", Encoding.UTF8, "application/json"),
StatusCode = HttpStatusCode.BadRequest
};
}
可是,swagger 中回傳的狀態碼卻是 0,

這是因為 Content 指定了 JSON 格式,但傳入的 content 又不是 JSON 格式的,
將 content 改為 JSON 格式,或者將 mediaType 改成 text/plain 就可以了,
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/54721.html
標籤:C#
下一篇:五、C#入門—流程控制
