从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; }
}
答案 0 :(得分:0)
如果是编码问题,请尝试自己构建内容并将其发送到服务器,
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以及服务器上收到的内容。