ASP.NET Core MVC使用MessagePack配合前端fetch交換數據

1.安裝Nuget包 - WebApiContrib.Core.Formatter.MessagePackhtml

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

2.配置Startup.csgithub

 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.添加控制器app

 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.jsfetch

5.編寫jsthis

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

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

而後開始測試GET和POST方法code

 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));

大功告成!orm

相關文章
相關標籤/搜索