我想使用 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 }}
在過去的兩天里,我一直在谷歌上搜索并嘗試了很多。但不幸的是,沒有任何效果。
這是我的模型
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 和資料庫模型來獲得經驗。
uj5u.com熱心網友回復:
由于您使用的是 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);
}
并修復發布操作
[HttpPost]
[Route("CreateLocation")]
public IActionResult CreateOrt([FromBody] Location location)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/440793.html
