简体   繁体   English

发布到 ASP.NET Core 3.1 Web 应用程序时,“[FromBody]MyClass 数据”通常为空

[英]When posting to an ASP.NET Core 3.1 web app, "[FromBody]MyClass data" is often null

I encountered this interesting (frustrating) problem recently after upgrading from .NET Core 2.2 to 3.1.我最近在从 .NET Core 2.2 升级到 3.1 后遇到了这个有趣(令人沮丧)的问题。 Previously I would POST data to the web app, with the receiving method looking something like this:以前,我会将数据 POST 到 Web 应用程序,接收方法如下所示:

public IActionResult OnPostAddNewDataAsync([FromBody]MyClass data)
{
    //...
}

where MyClass might be something like this:其中MyClass可能是这样的:

public class MyClass
{
    public string Field1 {get; set;}
    public integer Value1 {get; set;}
}

(For reference, to hit the endpoint from Javascript, you can do it like this: (作为参考,要从 Javascript 访问端点,您可以这样做:

 await PostDataAsync("AddNewData", {
      "Field1": "Hello I am",
      "Value1": 7
 });

async function PostDataAsync(handler, data)
{
    return await $.ajax({
        url: window.location.pathname + "?handler=" + handler,
        type: "POST",
        contentType: "application/json",
        headers:
        {
            RequestVerificationToken: $('input:hidden[name="__RequestVerificationToken"]').val()
        },
        data: JSON.stringify(data)
    });
}

it took me a while to figure that out!).我花了一段时间才弄明白!)。

This worked fine.这工作得很好。

After updating .NET Core 3.1, many of my POST methods stopped working, and the [FromBody] value would be null.更新 .NET Core 3.1 后,我的许多 POST 方法停止工作,并且[FromBody]值将为空。

Note: As part of my upgrade to .NET Core 3.1 I removed references to Newtonsoft.Json , deciding instead to try and use the new System.Text.Json .注意:作为升级到 .NET Core 3.1 的一部分,我删除了对Newtonsoft.Json引用,决定改为尝试使用新的System.Text.Json This would turn out to be important!这将变得很重要!

As mentioned, references to Newtonsoft.Json were removed, leaving any automatic Json conversion to be dealt with by System.Text.Json .如前所述,删除了对Newtonsoft.Json引用,留下任何自动 Json 转换由System.Text.Json处理。 It turns out that this was the cause of the problem as System.Text.Json is not as flexible (Microsoft themselves say so, and that it is intended to be so: How to migrate from Newtonsoft.Json to System.Text.Json) .事实证明,这是问题的原因,因为System.Text.Json不够灵活(微软自己这么说,而且它的目的是这样: 如何从 Newtonsoft.Json 迁移到 System.Text.Json) .

Before .NET Core 3, ASP.NET Core used Newtonsoft.Json internally, and now it uses System.Text.Json instead.在 .NET Core 3 之前,ASP.NET Core 在内部使用Newtonsoft.Json ,现在它使用System.Text.Json

An example is with a numeric field, eg MyClass.Value1 .一个例子是数字字段,例如MyClass.Value1 If from Javascript you pass "10" or 10, Newtonsoft.Json will cope with that and recognise both as 10. With System.Text.Json by default that field cannot have surrounding quotes, and if in the Json you posted it did you'd be getting a null [FromBody] value.如果从 Javascript 中传递“10”或 10, Newtonsoft.Json将处理它并将两者识别为 10。默认情况下System.Text.Json该字段不能有周围的引号,如果在 Json 中你发布了它d 得到一个空[FromBody]值。

The quickest solution to this problem is to revert to Newtonsoft.Json for these cases, and that is easily done by:解决这个问题的最快方法是在这些情况下恢复到Newtonsoft.Json ,这很容易通过:

  • installing the Nuget package Microsoft.AspNetCore.Mvc.NewtonsoftJson安装 Nuget 包Microsoft.AspNetCore.Mvc.NewtonsoftJson
  • in Startup.cs, update the following method as so:在 Startup.cs 中,更新以下方法:

. .

public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages().AddNewtonsoftJson();

    //All your other code:
    //...
}

This is taken directly from here .这是直接取自这里

Having made this change everything worked as expected again.进行此更改后,一切都再次按预期工作。

I am aware that System.Text.Json can be configured with custom parsers to handle these kind of situations (which I do use elsewhere), but I have dozens of POST methods and rather than updating all of them to work with the new way, it was a lot easier to do as described above.我知道System.Text.Json可以配置自定义解析器来处理这些情况(我确实在其他地方使用过),但我有几十个 POST 方法,而不是更新它们以使用新方法,如上所述,这样做要容易得多。

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

相关问题 在asp.net核心中调用asp.net mvc 5 Web api,FromBody始终为null - calling asp.net mvc 5 web api in asp.net core, FromBody always null Asp.net 核心 FromBody 总是得到 NULL - Asp.net core FromBody always getting NULL FromBody 在 ASP.NET 核心 API 返回 null - FromBody in ASP.NET Core API returns null 在 ASP.Net Core 5 MVC 控制器中,当传递包含小数的 JSON 对象 FromBody 时,模型始终为空 - In ASP.Net Core 5 MVC Controller, when passed a JSON object FromBody that contains a decimal the model is always null Asp.net 核心 3.1 保护 API 和 web 应用程序 - Asp.net core 3.1 securing API and web app 在 ASP.NET Core 中发布到控制器时,所有值都为空 - All values are null when posting to controller in ASP.NET Core HttpContext 是 ASP.Net Core 3.1 中的 null? - HttpContext is null in ASP.Net Core 3.1? ASP.net 核心 3.1,添加对 controller 动作自动绑定 [FromBody] 参数的依赖注入支持 - ASP.net core 3.1, add dependency injection support for controller actions auto bound [FromBody] parameters ASP.NET Core http post [FromBody] 在 3.1 中损坏,在 2.2 中使用 - ASP.NET Core http post [FromBody] broken in 3.1, used to work in 2.2 与 ASP.NET Core 中的 FromBody 混淆 - Confused with FromBody in ASP.NET Core
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM