gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:23:58 25 4
gpt4 key购买 nike

我们正在将网站从 ASP MVC .Net Framework 迁移到 .Net Core。在许多情况下,我们从页面向 Controller 发出 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# Controller :

[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 为 null):

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 装饰你的 Controller ,你可以省略这个属性

关于c# - 迁移到 ASP.Net Core MVC 时,JSON 序列化/反序列化不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60711693/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com