• ASP.NET Core MVC使用MessagePack配合前端fetch交换数据


    1.安装Nuget包 - WebApiContrib.Core.Formatter.MessagePack

    https://www.nuget.org/packages/WebApiContrib.Core.Formatter.MessagePack/

    2.配置Startup.cs

     1 public class Startup
     2     {
     3         public Startup(IConfiguration configuration)
     4         {
     5             Configuration = configuration;
     6         }
     7 
     8         public IConfiguration Configuration { get; }
     9 
    10         // This method gets called by the runtime. Use this method to add services to the container.
    11         public void ConfigureServices(IServiceCollection services)
    12         {
    13             services.AddMvc()
    14                 .AddMessagePackFormatters()
    15                 .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    16 
    17         }
    18     }

    3.添加控制器

     1     [Produces("application/x-msgpack")]
     2     public class TestController : Controller
     3     {
     4         public IActionResult Get()
     5         {
     6             return new ObjectResult(new TestDto()
     7             {
     8                 Name = "旋风小伙",
     9                 Age = 22,
    10             });
    11         }
    12 
    13         public IActionResult Post([FromBody]TestDto dto)
    14         {
    15             return new ObjectResult(raw);
    16         }
    17     }

    4.复制msgpack-lite的js到wwwroot/js目录下

    https://github.com/kawanet/msgpack-lite/blob/master/dist/msgpack.min.js

    5.编写js

    先把js引入到需要使用messagepack的cshtml文件中

    1         <script src="~/js/msgpack.min.js" asp-append-version="true"></script>

    然后开始测试GET和POST方法

     1     //测试POST方法
     2     fetch('/Test/Post', {
     3         method: 'POST',
     4         headers: {
     5             'Content-Type': 'application/x-msgpack'
     6         },
     7         body: msgpack.encode({ Name: "旋风小伙", Age: 22 })
     8     })
     9         .then(data => console.log(data))
    10         .catch(e => console.error(e));
    11 
    12     //测试GET方法
    13     fetch('/Login/Get')
    14         .then(data => data.arrayBuffer())
    15         .then(b => {
    16             //打印了一个对象
    17             console.log(msgpack.decode(new Uint8Array(b)));
    18         })
    19         .catch(e => console.error(e));

    大功告成!

  • 相关阅读:
    删除字符串前后的空格
    Python中定义“私有”成员变量和成员函数
    linux 线程
    进程虚拟内存模型
    守护进程
    FIFO
    linux 中的 wait 函数和 waitpid 函数
    孤儿进程和僵尸进程
    linux 中的 exec 函数族
    linux中的fork函数
  • 原文地址:https://www.cnblogs.com/myhalo/p/10502219.html
走看看 - 开发者的网上家园