我在WebApi中使用swagger的時候發現會出現很多問題,搜索很多地方都沒找到完全解決問題的方法,后面自己解決了,希望對於遇到同樣問題朋友有幫助。我將先一步一步的演示項目中解決swagger遇到問題及解決方法。
首先我們新建一個api項目

圖1 (默認生成項目)

圖2(運行首頁)

圖3(默認Api列表)

圖4(默認Get的Api)
以上圖1-4都是默認情況下生成頁面看起來不是那么好看,而且測試也不方便,下面將介紹怎么使用swagger。
使用nuget包獲取Swashbule、swagger的包並安裝。

圖5(Swashbule - swagger for Api)

圖6(swagger UI for net)
一般安裝到就應該可以正常運行了。但是運行后我們發現拋出異常

圖7(異常1)
打開解決方案屬性-->生成,勾選XML文檔文件,保存就ok。

圖8

圖9(異常2)
出現該異常是由於沒有增加依賴項,大家可以自行查看自己的dll文件版本,做出修改,把下面的代碼插入到web.config中。
|
1
2
3
4
5
6
7
8
9
10
11
12
|
<dependentAssembly>
<assemblyIdentity name=
"System.Net.Http.Formatting"
publicKeyToken=
"31bf3856ad364e35"
culture=
"neutral"
/>
<bindingRedirect oldVersion=
"0.0.0.0-5.0.0.0"
newVersion=
"5.0.0.0"
/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name=
"System.Web.Http"
publicKeyToken=
"31bf3856ad364e35"
culture=
"neutral"
/>
<bindingRedirect oldVersion=
"0.0.0.0-5.0.0.0"
newVersion=
"5.0.0.0"
/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name=
"Newtonsoft.Json"
publicKeyToken=
"30ad4fe6b2a6aeed"
culture=
"neutral"
/>
<bindingRedirect oldVersion=
"0.0.0.0-8.0.0.0"
newVersion=
"8.0.0.0"
/>
</dependentAssembly>
|
在把swagger.net中兩行代碼注釋,估計是因為nuget包中的代碼沒有更新導致這個異常出現

圖10(注釋不需要代碼)
好了現在我們來看看可以運行后的效果,在瀏覽器中輸入URL:http://localhost:28129/swagger會自動跳轉到http://localhost:28129/swagger/ui/index

圖11
至此我們就能夠正常運行swagger非常方便調試接口。
為了方便測試我們新建一個App的Model
/// <summary>
/// App信息
/// </summary>
public class App
{
/// <summary>
/// App的ID號
/// </summary>
public int Id { get; set; }
/// <summary>
/// App的名稱
/// </summary>
public string Name { get; set; }
/// <summary>
/// App的說明
/// </summary>
public string Remark { get; set; }
}
返回消息ResultJson的Model
/// <summary>
/// 返回處理結果
/// </summary>
public class ResultJson
{
/// <summary>
/// 返回代碼
/// </summary>
public int Code { get; set; }
/// <summary>
/// 返回消息
/// </summary>
public string Message { get; set; }
}
新增加一個AppController的Api
public class AppController : ApiController
{
private List<App> GetApps()
{
List<App> list = new List<App>();
list.Add(new App() { Id = 1, Name = "WeChat", Remark = "WeChat" });
list.Add(new App() { Id = 2, Name = "FaceBook", Remark = "FaceBook" });
list.Add(new App() { Id = 3, Name = "Google", Remark = "Google" });
list.Add(new App() { Id = 4, Name = "QQ", Remark = "QQ" });
return list;
}
/// <summary>
/// 獲取所有APP
/// </summary>
/// <returns>所有APP集合</returns>
[HttpGet]
public HttpResponseMessage Get()
{
return MyJson.ObjectToJson(GetApps());
}
/// <summary>
/// 獲取指定APP
/// </summary>
/// <param name="id">需要獲取APP的id</param>
/// <returns>返回指定APP</returns>
[HttpGet]
public HttpResponseMessage Get(int id)
{
var app = GetApps().Where(m => m.Id.Equals(id)).FirstOrDefault();
return MyJson.ObjectToJson(app);
}
/// <summary>
/// 增加App信息
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
[HttpPost]
public HttpResponseMessage Insert([FromBody]App value)
{
ResultJson json = new ResultJson() { Code = 200, Message = "Ok" };
return MyJson.ObjectToJson(json);
}
/// <summary>
/// 更新APP信息
/// </summary>
/// <param name="value">APP信息</param>
/// <returns>更新結果</returns>
[HttpPut]
public HttpResponseMessage UpdateApp([FromBody]App value)
{
ResultJson json = new ResultJson() { Code = 200, Message = "Ok" };
return MyJson.ObjectToJson(json);
}
/// <summary>
/// 刪除APP信息
/// </summary>
/// <param name="id">APP編號</param>
/// <returns>刪除結果</returns>
[HttpDelete]
public HttpResponseMessage DeleteApp(int id)
{
ResultJson json = new ResultJson() { Code = 200, Message = "Ok" };
return MyJson.ObjectToJson(json);
}
}
為了滿足使用中需要用到Json格式數據,提出一個類
public class MyJson
{
public static HttpResponseMessage ObjectToJson(object obj)
{
JavaScriptSerializer js = new JavaScriptSerializer();
string r = js.Serialize(obj);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(r, Encoding.UTF8, "text/json")
};
return result;
}
public static HttpResponseMessage ObjectToJson(List<object> objs)
{
JavaScriptSerializer js = new JavaScriptSerializer();
string r = js.Serialize(objs);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(r, Encoding.UTF8, "text/json")
};
return result;
}
}
好了我們運行后可以看看效果

圖12
點擊 Try it out

圖13
我們還可以將注釋打開,我們就可以在頁面里面看到注釋,方便調試接口時候調用人了解各參數信息。打開
public class SwaggerConfig
{
public static void Register()
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.SingleApiVersion("v1", "SwaggerApiDemo");
c.IncludeXmlComments(GetXmlCommentsPath());
})
.EnableSwaggerUi(c =>
{
});
}
private static string GetXmlCommentsPath()
{
return string.Format("{0}/bin/SwaggerApiDemo.XML", System.AppDomain.CurrentDomain.BaseDirectory);
}
}
上面標記顏色為新增加內容,好了我們來看看最終效果

圖14

圖15
我們可以看到注釋部分了,這樣我們的swagger就完成了。
我把最終的代碼發到此處,有需要代碼的時候朋友可以直接下載。
http://pan.baidu.com/s/1mhFVZ4W

