虽然都推荐使用[FromBody]自动推断类型的属性,但我还是去玩了一下

首先就是需要安装两个包

Microsoft.AspNetCore.Mvc.NewtonsoftJson
Newtonsoft.Json

配置 Startup

services.AddControllers()
        .AddNewtonsoftJson()
        .ConfigureApiBehaviorOptions(options =>
        {
            // 禁用自动推断
            options.SuppressInferBindingSourcesForParameters = true;
        });

ConfigureApiBehaviorOptions 可以参考以下链接

https://www.cnblogs.com/qianxingmu/p/12960764.html

Post 方式传递 Json 数据

[HttpPost("DoLogin")]
public IActionResult DoLogin([FromBody] JObject value)
{
    var jsonStr = JsonConvert.SerializeObject(value);
    var jsonParams = JsonConvert.DeserializeObject<dynamic>(jsonStr);

    //根据 key 取出 value
    string username = jsonParams["Username"];
    string password = jsonParams["Password"];
}

ASP.NET Core 3.x [FromBody] 传递 Json 字符串 结束

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-12-28
  • 2022-02-20
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-11-13
  • 2022-12-23
  • 2022-12-23
  • 2021-10-24
  • 2021-11-19
  • 2022-12-23
相关资源
相似解决方案