无法通过 POST 带有空子类 Net Core API 的嵌套 JSON 发送

Can't send via POST a nested JSON with null Subclass Net Core API

我想使用 c# 将带有子对象的对象作为 Json 发送到我的 Net Core API。如果子对象已填充,则此方法有效。但是一旦子对象为空,它就不会到达控制器。我收到状态代码为 400 的错误。

    StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:{  Date: Thu, 10 Mar 2022 09:40:25 GMT Server: Kestrel Content Length: 296 Content-Type: application/problem+json; charset=utf-8 }}

过去 2 天我一直在谷歌上搜索并尝试了很多。但不幸的是没有任何效果。

这是我的模型

   public class Location
   {
        [Key]
        public string Zipcode{ get; set; }
        public string LocationName { get; set; }
        public DateTime CreationDate{ get; set; }

        [ForeignKey("Street")]
        public string StreetID{ get; set; }
        public virtual Street Street{ get; set; }
    }

    public class Street
    {
        [Key]
        public string StreetName { get; set; }
    }

这是我的请求

            HttpClient httpClient = new HttpClient();
            string requestUri = "https://localhost:5001/Customers/CreateLocation";
            
            var json = JsonConvert.SerializeObject(location);
            var buffer = System.Text.Encoding.UTF8.GetBytes(json);
            var byteContent = new ByteArrayContent(buffer);
            byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            var response = await httpClient.PostAsync(requestUri, byteContent);
            string result = response.Content.ReadAsStringAsync().Result;

这是我的控制器

        [HttpPost]
        [Route("CreateLocation")]
        public IActionResult CreateOrt(Location location)
        {
            location = KundenRepositorie.CreateLocation(Bankdaten_DB, location);
            return CreatedAtAction("GetCustomerByID", new { id = location.Zipcode}, location);
        }

我已经将以下内容添加到 Programm.cs

builder.Services.AddControllers().AddNewtonsoftJson();
builder.Services.AddControllers().AddJsonOptions(options =>
{
   options.JsonSerializerOptions.DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull;
});

这个Json工作正常并到达控制器

{"Zipcode":"89898",
 "LocationName ":"MyCity",
 "CreationDate":"2022-03-10T11:01:25.9840573+01:00",
 "StreedID":"Am Dorf",
 "Street":
          {"StreetName ":"Am Dorf",
            "Kunden":null}
}

但是我收到了错误消息,但它没有到达

{"Zipcode":"89898",
    "LocationName":"MyCity",
    "CreationDate":"2022-03-10T11:12:39.8402702+01:00",
    "StreedID":null,
    "Street":null}

非常感谢任何帮助提示。也许我做的事情从根本上是错误的。我在这里自学并试验 API 和数据库模型以获取经验。

由于您使用的是 net 6 ,因此必须使所有内容都可以为空,这就是出现错误的原因 你可以试试这个

public class Location
   {
        .....
        public string? StreetID{ get; set; }
        public virtual Street? Street{ get; set; }
    }

但我建议您通过从项目属性中删除 nullable 来修复所有问题,否则它会不断重复

<PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <!--<Nullable>enable</Nullable>-->
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

然后修复程序,你加了两次控制器,应该是一次

builder.Services.AddControllers()
.AddNewtonsoftJson(options =>
  options.SerializerSettings.ContractResolver =
        new CamelCasePropertyNamesContractResolver());

然后修复你的 http 请求,你不需要任何字节数组,因为你正在发送 json

    string requestUri = "https://localhost:5001/Customers/CreateLocation";
using HttpClient client = new HttpClient();

client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

 var json = JsonConvert.SerializeObject(location);
var content = new StringContent(json, UTF8Encoding.UTF8, "application/json");    
  
var response = await client.PostAsync(requestUri, content);     

if (response.IsSuccessStatusCode)
    {
        var stringData = await response.Content.ReadAsStringAsync();
        var result = JsonConvert.DeserializeObject<object>(stringData);
    }   

并修复 post 操作

         [HttpPost]
        [Route("CreateLocation")]
        public IActionResult CreateOrt([FromBody] Location location)