【发布时间】:2022-11-15 02:00:38
【问题描述】:
我正在尝试使用 POST 方法和以下 JSON 主体访问公共 API:
{
"params": {
"companyId":"620e91a211b42421733aa2b4"
},
"id": "620e91a211b42421733aa2b4",
"jsonrpc": "2.0", "method": "getLicenseInfo"
}
这会正确返回 Postman 中的预期值。 不幸的是,在使用以下代码后,我在通过 C# asp.net 应用程序发送请求时遇到了问题:
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, GlobalFunctions.GetBitDefenderBaseURL() + "/licensing");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Headers.Add("cache-control", "no-cache");
request.Headers.Add("Connection", "keep-alive");
request.Headers.Add("user-agent", "ReservedArea/1.0");
string base64Token = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(GlobalFunctions.GetBitDefenderAPIKey() + ":"));
request.Headers.Add("Authorization","Basic " + base64Token );
string json = "{\"params\": {" +
"\"companyId\":\"" + bitDefenderCompanyId + "\"}," +
"\"id\": \"" + bitDefenderCompanyId + "\"," +
"\"jsonrpc\": \"2.0\"," +
"\"method\": \"getLicenseInfo\"}";
var httpContent = new System.Net.Http.StringContent(json, Encoding.UTF8, "application/json");
request.Content = httpContent;
HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false);
我收到“不支持的媒体类型错误”。
据我了解,我在创建 StringContent 对象时正确指定了请求内容类型,但是我没有从我尝试联系的 API 获得正确响应的运气。
非常感谢任何渴望帮助我的人。
【问题讨论】:
-
是
clientHttpClient? -
是的,客户端是HTTP
-
http 客户端上还有其他重载,例如
PostJsonAsync。你能试试看吗?它更简单并且需要更少的代码,这总是更好。 -
我试过了,但我仍然遇到同样的错误。
标签: c# asp.net json api http-status-code-415