[英]JSON serialization/deserialization not working when migrating to ASP.Net Core MVC
我们正在将一个站点从 ASP MVC .Net Framework 迁移到 .Net Core。 在很多情况下,我们从页面到控制器做 ajax POST 请求:
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();
}
});
[HttpPost]
public async Task<JsonResult> foo(FooRequest request)
{
//request.Name is empty
return Json(new { msg = "Success" });
}
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();
});
...但它们都不起作用。
我从 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.