Isk*_*yev 1 .net c# http postman
我试图通过C#(.NET Core 2.2.104)向主体中的外部Web服务发出带有application / json的HTTP POST请求。
我已经阅读了SO中的所有类似问题,并编写了以下代码:
SignXmlRequestDto requestBody = new SignXmlRequestDto(p12, model.SignCertPin, model.Data);
string json = JsonConvert.SerializeObject(requestBody);
var httpRequestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = ncanNodeUrl,
Headers =
{
{ HttpRequestHeader.ContentType.ToString(), "application/json" }
},
Content = new StringContent(JsonConvert.SerializeObject(json))
};
var response = await httpClient.SendAsync(httpRequestMessage);
string responseString = await response.Content.ReadAsStringAsync();
Run Code Online (Sandbox Code Playgroud)
我从服务中收到一个错误,它说:“无效的标头Content-Type。请将Content-Type设置为application / json”。在这里有趣的是,如果我模拟了来自Postman的请求,那么一切正常,我得到了成功的响应。
更新:按照@KristófTóth的建议,我将代码修改为:
var httpRequestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = ncanNodeUrl,
Content = new StringContent(json, Encoding.UTF8, "application/json")
};
var response = await httpClient.SendAsync(httpRequestMessage);
string responseString = await response.Content.ReadAsStringAsync();
Run Code Online (Sandbox Code Playgroud)
但是它仍然给我同样的错误信息。
Content-Type是内容标头。应该在内容上设置,而不是在请求本身上设置。这可以使用StringContent(string,Encoding,string)构造函数完成:
Content = new StringContent(JsonConvert.SerializeObject(json),Encoding.UTF8, "application/json")
Run Code Online (Sandbox Code Playgroud)
或通过设置StringContent的Headers.ContentType属性:
var content=new StringContent(JsonConvert.SerializeObject(json));
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
66 次 |
| 最近记录: |