繁体   English   中英

迁移到 ASP.Net Core MVC 时 JSON 序列化/反序列化不起作用

[英]JSON serialization/deserialization not working when migrating to ASP.Net Core MVC

我们正在将一个站点从 ASP MVC .Net Framework 迁移到 .Net Core。 在很多情况下,我们从页面到控制器做 ajax POST 请求:

js:

var request = { Name: "bar" };
$.ajax({
    url: "/Home/foo",
    type: "POST",
    data: JSON.stringify(request),
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    success: function (response) {
        console.log();
    }
});

C# 控制器:

[HttpPost]
public async Task<JsonResult> foo(FooRequest request)
{
    //request.Name is empty
    return Json(new { msg = "Success" });
}

c#模型:

public class FooRequest
{
    public string Name { get; set; }
}

这一切都适用于 .Net Framework,但在 Core失败,因为接收到的对象的所有属性都是 null

我试过同时使用AddJsonOptions

services.AddControllersWithViews()
    .AddJsonOptions(option =>
    {
        option.JsonSerializerOptions.PropertyNamingPolicy = null;
        option.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
    });

...和AddNewtonsoftJson

services.AddControllersWithViews()
    .AddNewtonsoftJson(option =>
    {
        option.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
    });

...但它们都不起作用。

我需要做什么才能在 .Net Core 中获得与在 .Net Framework 中相同的行为?

更新

我从 Postman 调用 endint 得到相同的行为(request.Name 为空):

POST /home/foo HTTP/1.1
Host: localhost:44393
Content-Type: application/json

{ "Name": "bar" }

我还尝试序列化请求:

var request = { Name: "bar" };
$.ajax({
    url: "/Home/foo",
    type: "POST",
    data: request,
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    success: function (response) {
        console.log();
    }
});

...但结果相同

尝试将FromBodyAttribute添加到您的参数中:

[HttpPost]
public async Task<JsonResult> foo([FromBody] FooRequest request)
{
    //request.Name is empty
    return Json(new { msg = "Success" });
}

你可以省略这个属性,如果你用ApiControllerAttribute装饰你的控制器

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM