我有以下代码向外部端点发出 HTTP 请求,这会抛出一个 422 状态代码,它是不可处理的实体。当使用 Postman 直接调用外部 URL 时,相同的请求负载可以正常工作。
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var Json = JsonConvert.SerializeObject(loanRequest, new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver
{
IgnoreSerializableAttribute = false
}
});
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "externalEndPointURL");
request.Content = new StringContent(Json,Encoding.UTF8,"application/json");//CONTENT-TYPE header
HttpContent httpContent = new StringContent(Json, Encoding.UTF8, "application/json");
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("content-type", "application/json; charset=utf-8");
httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.AccessToken}");
await httpClient.SendAsync(request).ContinueWith(task => {
Console.WriteLine($"Response {task.Result}");
});
}
//请求负载
{
"Merchant": "GAP",
"Lender": "BEN",
"RateType": "VAR",
"RepaymentType": "PI",
"PropertyUsage": "INV",
"CustomerRate": 0.0429,
"LoanTerm": 20,
"BorrowingAmount": 600000,
"RateTerm": null
}
编辑
下面是两个请求头的比较。