Dynamic Payloads in ASP.NET Core

栏目: IT技术 · 发布时间: 4年前

内容简介:It has always been possible (but atad problematic) to submit dynamic contents to an ASP.NET Core controller action. In the dark, pre-Core days, we had to implement a custom model binder for this. Now it is no longer the case.All we need is to declare an ac

It has always been possible (but atad problematic) to submit dynamic contents to an ASP.NET Core controller action. In the dark, pre-Core days, we had to implement a custom model binder for this. Now it is no longer the case.

All we need is to declare an action method as having a dynamic parameter, obtained from the request body, and accepting the request through POST:

[HttpPost]
public IActionResult Post([FromBody] dynamic payload)
{
    return Json(new { Ok = true });
}

This will accept any content that we POST, if we use the Content Type application/json , and it will by default be turned into a System.Text.Json.JsonElement , a type of the new JSON API, which is the default serializer of ASP.NET Core 3.

If, for some reason, we want to go back to the previous serializer, JSON.NET ( Newtonsoft.Json ), we need to do a couple of things:

  1. Install the Microsoft.AspNetCore.Mvc.NewtonsoftJson Nuget package (it will bring all of the necessary dependencies)

  2. Configure it as the default serializer ( AddMvc or AddControllers or AddRazorPages or AddControllersWithViews all allow this):

    services
    .AddMvc()
    .AddNewtonsoftJson();

If you do, the payload will instead by a Newtonsoft.Json.Linq.JObject instance. The main difference between the two serializer is outlined here . In the end, System.Text.Json supports most of the usual cases and is already included.

In general, I prefer using strongly-typed models, but there may be use cases for this, particularly when implementing routers, API gateways or similar functionality.

As always, hope this is useful! Dynamic Payloads in ASP.NET Core


以上所述就是小编给大家介绍的《Dynamic Payloads in ASP.NET Core》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

长尾理论2.0

长尾理论2.0

安德森 / 乔江涛、石晓燕 / 中信出版社 / 2009-5 / 42.00元

《长尾理论2.0》是克里斯·安德森对所有问题最明确的回答。在此书中,他详细阐释了长尾的精华所在,揭示了长尾现象是如何从工业资本主义原动力——规模经济与范围经济——的矛盾中产生出来的。长尾现象虽然是明显的互联网现象,但其商务逻辑本身,却是从工业经济中自然而然“长”出来的,网络只是把酝酿了几十年的供应链革命的诸多要素简单地结合在一起了。同时,长尾理论转化为行动,最有力、最可操作的就是营销长尾,通过口碑......一起来看看 《长尾理论2.0》 这本书的介绍吧!

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具