简体   繁体   English

FromBody 在 ASP.NET 核心 API 返回 null

[英]FromBody in ASP.NET Core API returns null

I have created a stateful ASP.NET Core service with 10 partitions in Azure Service Fabric with API as the project template and ASP.NET Core 3.0. I have created a stateful ASP.NET Core service with 10 partitions in Azure Service Fabric with API as the project template and ASP.NET Core 3.0. I am trying to send an object of class SupplierMaterialMaintenance through Postman in JSON to my stateful service as shown in the figure below:- I am trying to send an object of class SupplierMaterialMaintenance through Postman in JSON to my stateful service as shown in the figure below:-

在此处输入图像描述

Here is the JSON file that I am trying to send.这是我要发送的 JSON 文件。

{
    "SupplierMaterialAssociationGuid": "6ef61a2b-963e-4993-ac73-5e07f707c2e2",
    "MinimumOrderQuantity": 1,
    "UnitOfMeasurementGuid": "771d4f76-9321-442f-b2c2-9f75b1a7cda8",
    "ConversionFactor": 2,
    "POPrice": 123.00000,
    "OrderLeadTime": 10,
    "IssueMinimumLot": 0,
    "ContainerQuantity": 10,
    "InnerContainerQuantity": 1,
    "NoOfInnerContainers": 10,
    "SupplierMaterialNumber": null,
    "SupplierMaterialName": null,
    "POPriceExcludingMetal": 123.00000,
    "InitialVolumeQuantity": 1,
    "ReplacementMaterialNumber": "",
    "MetalWeight": 0.0,
    "MetalRate": 0.0,
    "StandardBoxLength": 0.0,
    "StandardBoxHeight": 0.0,
    "StandardBoxWidth": 0.0,
    "StandardPackFactor": 10,
    "FullBoxWeight": 0.0,
    "TariffCodeGuid": "00000000-0000-0000-0000-000000000000",
    "CountryRegionsAssociationGuid": "00000000-0000-0000-0000-000000000000",
    "ExpiryDate": "0001-01-01T00:00:00",
    "IsActive": true,
    "MatSuppMainSupplier": false,
    "EUPreferentialOriginStatusCode": null,
    "Id": "ead6cbc7-baff-430d-b83b-4914a916aabd",
    "Name": null,
    "CreatedDate": "2019-07-09T01:53:49.659194",
    "ModifiedDate": "2019-07-09T01:53:49.659194",
    "CreatedBy": "13beef85-3939-4998-b912-22d8df2cd966",
    "ModifiedBy": "13beef85-3939-4998-b912-22d8df2cd966",
    "IsRowChecked": false,
    "Version": null,
    "CrudOperationType": 0,
    "Error": null
}

And here is my controller:-这是我的 controller:-

using Microsoft.AspNetCore.Mvc;
using Microsoft.ServiceFabric.Data;
using Microsoft.ServiceFabric.Data.Collections;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MyStatefulService.Models;
using System.Net.Http;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;

namespace MyStatefulService.Controllers
{
    [Produces("application/json")]
    [Route("api/[controller]")]
    [ApiController]
    public class DefaultController : Controller
    {
        private readonly IReliableStateManager reliableStateManager;

        public DefaultController(IReliableStateManager reliableStateManager)
        {
            this.reliableStateManager = reliableStateManager;
        }

        // GET api/Default
        [HttpGet]
        public async Task<IActionResult> Get()
        {
            CancellationToken ct = new CancellationToken();

            IReliableDictionary<Guid, SupplierMaterialMaintenance> myDictionary = await this.reliableStateManager.GetOrAddAsync<IReliableDictionary<Guid, SupplierMaterialMaintenance>>("dictionary");

            using (ITransaction tx = this.reliableStateManager.CreateTransaction())
            {
                Microsoft.ServiceFabric.Data.IAsyncEnumerable<KeyValuePair<Guid, SupplierMaterialMaintenance>> list = await myDictionary.CreateEnumerableAsync(tx);

                Microsoft.ServiceFabric.Data.IAsyncEnumerator<KeyValuePair<Guid, SupplierMaterialMaintenance>> enumerator = list.GetAsyncEnumerator();

                List<KeyValuePair<Guid, SupplierMaterialMaintenance>> result = new List<KeyValuePair<Guid, SupplierMaterialMaintenance>>();

                while (await enumerator.MoveNextAsync(ct))
                {
                    result.Add(enumerator.Current);
                }

                return this.Json(result);
            }
        }

        // PUT api/Default/name
        [HttpPost]
        public async Task<IActionResult> Post([FromBody] SupplierMaterialMaintenance obj)
        {
            SupplierMaterialMaintenance obj1 = new SupplierMaterialMaintenance();
            if (ModelState.IsValid)
            {
                obj1 = obj;
            }
            IReliableDictionary<Guid, SupplierMaterialMaintenance> myDictionary = await this.reliableStateManager.GetOrAddAsync<IReliableDictionary<Guid, SupplierMaterialMaintenance>>("dictionary");

            using (ITransaction tx = this.reliableStateManager.CreateTransaction())
            {
                await myDictionary.AddOrUpdateAsync(tx, obj1.SupplierMaterialAssociationGuid, obj1, (key, oldvalue) => obj1);
                await tx.CommitAsync();
            }

            return new OkResult();
        }
    }
}

And here is the class SupplierMaterialMaintenance:-这是 class 供应商材料维护:-

public class SupplierMaterialMaintenance : IComparable<SupplierMaterialMaintenance>, IEquatable<SupplierMaterialMaintenance>
    {

        public Guid SupplierMaterialAssociationGuid;
        public int MinimumOrderQuantity;
        public Guid UnitOfMeasurementGuid;
        public int ConversionFactor;
        public decimal POPrice;
        public int OrderLeadTime;
        public int IssueMinimumLot;
        public int ContainerQuantity;
        public int InnerContainerQuantity;
        public int NoOfInnerContainers;
        public string SupplierMaterialNumber;
        public string SupplierMaterialName;
        public decimal POPriceExcludingMetal;
        public int InitialVolumeQuantity;
        public string ReplacementMaterialNumber;
        public decimal MetalWeight;
        public decimal MetalRate;
        public decimal StandardBoxLength;
        public decimal StandardBoxHeight;
        public decimal StandardBoxWidth;
        public int StandardPackFactor;
        public decimal FullBoxWeight;
        public Guid TariffCodeGuid;
        public Guid CountryRegionsAssociationGuid;
        public DateTime ExpiryDate;
        public bool IsActive;
        public bool MatSuppMainSupplier;
        public string EUPreferentialOriginStatusCode;
        public Guid Id;
        public string Name;
        public string CreatedDate;
        public string ModifiedDate;
        public Guid CreatedBy;
        public Guid ModifiedBy;
        public bool IsRowChecked;
        public string Version;
        public int CrudOperationType;
        public string Error;

        public int CompareTo(SupplierMaterialMaintenance obj)
        {
            if (obj != null)
            {
                SupplierMaterialMaintenance otherObj = obj as SupplierMaterialMaintenance;

                if (otherObj != null)
                {
                    return otherObj.SupplierMaterialAssociationGuid.CompareTo(this.SupplierMaterialAssociationGuid);
                }
                else
                {
                    throw new ArgumentException("Object is not a SupplierMaterialMaintenance");
                }
            }
            return 1;
        }

        public bool Equals(SupplierMaterialMaintenance obj)
        {
            if (obj == null) return false;

            return obj.SupplierMaterialAssociationGuid.Equals(this.SupplierMaterialAssociationGuid);
        }
    }

Whenever I hit the send button in Postman, I am always getting an object of class X initialised with default values as shown below:-每当我点击 Postman 中的发送按钮时,我总是得到一个 object 的 class X 初始化为默认值,如下所示: -

在此处输入图像描述

I have searched numerous questions on StackOverflow but to no success.我在 StackOverflow 上搜索了很多问题,但没有成功。 What am I doing wrong here?我在这里做错了什么?

You need to change all of your fields in the SupplierMaterialMaintenance class to the properties with getter and setter您需要将SupplierMaterialMaintenance class 中的所有fields更改为带有gettersetterproperties

public class SupplierMaterialMaintenance : IComparable<SupplierMaterialMaintenance>, IEquatable<SupplierMaterialMaintenance>
{
    public Guid SupplierMaterialAssociationGuid { get; set; }
    public int MinimumOrderQuantity { get; set; }
    public Guid UnitOfMeasurementGuid { get; set; }
    public int ConversionFactor { get; set; }
    //goes like this...

You can take a look at Microsoft Documentation about Model Binding in .net-core您可以查看有关 .net-core 中的.net-core绑定的Microsoft 文档

Since it's ASP.NET Core 3.0: are you still using NewtonSoft,Json, or have you switched to System.Text.Json ?既然是ASP.NET Core 3.0:你还在用NewtonSoft,Json,还是切换到System.Text.Json

ASP.NET Core by default serializes to and from Json using camelCase on the Json end.默认情况下,ASP.NET 内核在 Json 端使用驼峰式大小写与 Json 进行序列化。 So the data you're trying to post should look something like因此,您尝试发布的数据应该类似于

{

    "supplierMaterialAssociationGuid": "6ef61a2b-963e-4993-ac73-5e07f707c2e2",
    "minimumOrderQuantity": 1,
    "unitOfMeasurementGuid": "771d4f76-9321-442f-b2c2-9f75b1a7cda8",
    "conversionFactor": 2,

    ...

}

Taken from this NewtonSoft.Json Serialization Guide , using Fields should work just fine if you're working with NewtonSoft.Json and are manually (de)serializing .取自此 NewtonSoft.Json序列化指南,如果您正在使用 NewtonSoft.Json并且手动(反)序列化,则使用字段应该可以正常工作。 For model binding, you need to use properties as explained in the answer from darcane .对于 model 绑定,您需要使用darcane 的答案中解释的属性。

By default a type's properties are serialized in opt-out mode.默认情况下,类型的属性以退出模式序列化。 What that means is that all public fields and properties with getters are automatically serialized to JSON, and fields and properties that shouldn't be serialized are opted-out by placing JsonIgnoreAttribute on them.这意味着所有带有 getter 的公共字段和属性都会自动序列化为 JSON,并且通过在其上放置 JsonIgnoreAttribute 来选择不应该序列化的字段和属性。

声明:本站的技术帖子网页,遵循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 与 ASP.NET Core 中的 FromBody 混淆 - Confused with FromBody in ASP.NET Core ASP.NET 核心 - [FromBody] 的奇怪行为 - ASP.NET Core - weird behavior with [FromBody] ASP.NET Core 3.0 [FromBody] 字符串内容返回“无法将 JSON 值转换为 System.String。” - ASP.NET Core 3.0 [FromBody] string content returns "The JSON value could not be converted to System.String." 通过[FromBody]到MongoDB GeoJsonObjectModel成员的POST / PUT到ASP.Net Core始终为null - POST/PUT to ASP.Net Core with [FromBody] to a MongoDB GeoJsonObjectModel member is always null 发布到 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 在 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 内核 Ajax 返回 null - ASP.NET Core Ajax returns null 在ASP.NET Core MVC中无法调用具有类参数带有[FromBody]属性的类的API Post方法 - Unable to call API Post Method that has a class parameter with [FromBody] attribute in asp.net core mvc
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM