net WebApi中使用swagger
我在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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
2015-05-05 Moq 和RhinoMocks
2015-05-05 Wakatime 测试工作时间
2014-05-05 GridView动态增加行
2013-05-05 ArcEngine IMap接口
2013-05-05 Database2Sharp之混合型Winform框架代码生成
2013-05-05 vim配置文件和插件
2013-05-05 .NET:在ASP.NET中如何进行IP限制