[英]Post with HttpClient doesn't bind model
從azure函數到API的簡單文章
using (var response = await httpClient.PostAsJsonAsync(installationServiceUrl, deviceInstallation.ToRequestBody()))
{...}
但是Request.Content
不為null,並且包含發送的JSON
對象。 Content-Type標頭設置為application / json。
有什么建議么?
更新:據我了解,API如何認為Model是簡單的字符串值( locationId
),至少這是我從ModelState.Keys
集合中了解到的。 它僅包含locationId
。
更新: ToRequestBody
方法僅更改對象的形狀
public static DeviceInstallationRequest ToRequestBody(this DeviceInstallation deviceInstallation)
{
return new DeviceInstallationRequest()
{
InstallationId = deviceInstallation.InstallationId,
Name = deviceInstallation.Name,
StartDateTime = deviceInstallation.StartDateTime,
EndDateTime = deviceInstallation.EndDateTime,
CreatedDateTime = deviceInstallation.CreatedDateTime,
InstallationType = deviceInstallation.InstallationType,
Production = deviceInstallation.Production,
Default = deviceInstallation.Default
}
}
API方面的預期模型:
public class BindDeviceInstallationRequest
{
[Required]
public string InstallationId { get; set; }
[Required]
public string Name { get; set; }
[Required]
public DateTime StartDateTime { get; set; }
[Required]
public DateTime EndDateTime { get; set; }
[Required]
public DateTime CreatedDateTime { get; set; }
[Required]
public InstallationType InstallationType { get; set; }
[Required]
public bool Production { get; set; }
[Required]
public bool Default { get; set; }
}
如果是編碼問題,請嘗試自己構建內容並將其發送到服務器,
DeviceInstallationRequest model = deviceInstallation.ToRequestBody();
string json = JsonConvert.SerializeObject(model);
var content = new StringContent(json, Encoding.UTF8, "application/json");
using (var response = await httpClient.PostAsync(installationServiceUrl, content)) {
//...
}
這樣,您就可以完全控制要發送到服務器的內容。
調試時,檢查來自客戶端的原始JSON以及服務器上接收到的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.