我试图通过C#(.NET Core 2.2.104)向体内的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();
我从服务中收到一个错误,它说:“无效的标题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();
但是它仍然给我同样的错误信息。
答案 0 :(得分:5)
Content-Type是 content 标头。应该在内容上设置,而不是在请求本身上设置。这可以通过使用StringContent(string,Encoding,string)构造函数来完成:
Content = new StringContent(JsonConvert.SerializeObject(json),Encoding.UTF8, "application/json")
或通过设置StringContent的Headers.ContentType属性:
var content=new StringContent(JsonConvert.SerializeObject(json));
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
答案 1 :(得分:3)
这可能是编码问题。您应该使用JsonContent而不是StringContent,或者可以执行类似的操作:
pywinauto.findwindows.ElementNotFoundError: {'top_level_only': False, 'title': 47.0, 'control_type': 'Alloy.CustomControls.IntechTextBox', 'parent': <win32_element_info.HwndElementInfo - '', WindowsForms10.Window.8.app.0.13965fa_r6_ad1, 2034254>, 'backend': 'uia'}