zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    钉钉小程序解析html的方法
    git使用
    electron-vue项目
    数组方法大全
    关于AJAX
    常用的东西
    常用正则表达式
    选项卡
    进度条
    泛型单列
  • 原文地址:https://www.cnblogs.com/lyyd/p/11002307.html
Copyright © 2011-2022 走看看