WebAPI学习及Swagger使用

本文用来保存自己学习WebAPI和Swagger使用过程中参考的文章,以及对WebAPI的初步了解。

1.RESTful风格

WebAPI只支持Http协议;

 

1.1.WebAPI与MVC的区别

ValuesController

区别一:存在API控制器都使用的基类:ApiController

区别二:控制器中的方法返回原始对象,不是视图

区别三:MVC和WebAPI传统调度之间的差异。MVC根据名称调度操作,WebAPI默认根据动词调度操作

ApiController上的ExecuteAsync方法是接口IHttpController中的方法。,那么所有WebAPI控制器都是异步设计。

 

1.2.HttpResponseMessage和HttpRequestMessage

 

WebAPI默认返回XML格式文件,返回Json解决方案:

复制代码
 1 public class JsonContentNegotiator : IContentNegotiator
 2 
 3     {
 4 
 5         private readonly JsonMediaTypeFormatter _jsonFormatter;
 6 
 7         public JsonContentNegotiator(JsonMediaTypeFormatter formatter)
 8 
 9         {
10 
11             _jsonFormatter = formatter;
12 
13         }
14 
15         public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
16 
17         {
18 
19             var result = new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json"));
20 
21             return result;
22 
23         }
24 
25     }
JsonContentNegotiator
复制代码

WebApiConfig.cs中添加如下代码

复制代码
 1 public static void Register(HttpConfiguration config)
 2 
 3         {
 4 
 5             //返回JSON
 6 
 7             var jsonFormatter = new JsonMediaTypeFormatter();
 8 
 9             config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));
10 
11 }
Register
复制代码

参考:https://blog.csdn.net/xhsunnycsdn/article/details/81128699

2.Swagger使用

下面两篇文章,是自己认为较经典的。第二篇有关于Swagger实现原理的介绍

参考:

https://www.cnblogs.com/lhbshg/p/8711604.html

https://www.cnblogs.com/Leo_wl/p/5728033.html  //主要了解Swagger实现原理(ApiExplorer

3.权限验证

下面博文有关WebAPI的权限认证介绍

https://www.cnblogs.com/huangenai/p/5253709.html

4.跨域请求

https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api

posted @   鲁燕云端  阅读(392)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示