将JSON传递给API时,HttpClient.PostAsync会导致400错误

时间:2016-01-28 22:28:16

标签: json api asp.net-core bugzilla

我正在尝试将一些JSON格式的数据传递给Bugzilla API,但我收到了Files are included based on the file path given or, if none is given, the include_path specified.响应。我使用400来生成JSON,我可以告诉它生成的正常,所以我不确定是什么导致了400错误。

代码:

Netwonsoft.Json

它似乎生成的JSON是:

var Client = new HttpClient();

Dictionary <string, string> BugData = new Dictionary<string, string>
{
    { "Bugzilla_api_key", "Removed for scurity" },
    { "product", "Test" },
    { "component", "Test Component" },
    { "version", "unspecified" },
    { "summary", "Basic API Test" },
    { "description", "A basic API test" }
};

string Json = JsonConvert.SerializeObject(BugData, Formatting.Indented);

var Response = await Client.PostAsync("http://bugzillaaddress/rest/bug", new StringContent(Json, Encoding.UTF8, "application/json"));

我在这里做错了什么想法?

完整错误回复:

{
    "Bugzilla_api_key": "Removed for security",
    "product": "Test",
    "component": "Test Component",
    "version": "unspecified",
    "summary": "Basic API Test",
    "description": "A basic API test"
} 

这就是Fiddler所看到的:

  

POST http://bugzilla-tools/rest/bug HTTP / 1.1内容类型:   应用/ JSON; charset = utf-8连接:Keep-Alive内容长度:   193主持人:bugzilla-tools

     

{“Bugzilla_api_key”:“已移除   安全“‘产品’:‘试验’,‘分量’:”测试   组件“,”版本“:”未指定“,”摘要“:”基本API   测试“,”描述“:”基本API测试“}

编辑:来自Bugzilla团队的回应

我显然没有在我的请求中传递一个Accept标头。如果我添加一个接受标题我应该是好的。谁知道怎么做? (我现在正在寻找并玩弄东西但是如果有人有代码我可以复制并过去结束4天与这个API的战斗会很棒!)

1 个答案:

答案 0 :(得分:1)

我设法进入了我的电脑。这是一些示例代码。

var Client = new HttpClient();

Dictionary <string, string> BugData = new Dictionary<string, string>
{
    { "Bugzilla_api_key", "Removed for scurity" },
    { "product", "Test" },
    { "component", "Test Component" },
    { "version", "unspecified" },
    { "summary", "Basic API Test" },
    { "description", "A basic API test" }
};

string Json = JsonConvert.SerializeObject(BugData, Formatting.Indented);

var request = new HttpRequestMessage(HttpMethod.Post, "http://bugzillaaddress/rest/bug");

request.Content = new StringContent(Json, Encoding.UTF8, "application/json")
request.Headers.Add("Accept", "application/json");

var Response = await Client.SendAsync(request);

修改

我实际上已经注意到您也可以使用PostAsync执行此操作。

将其更改为此。

var Client = new HttpClient();

Dictionary <string, string> BugData = new Dictionary<string, string>
{
    { "Bugzilla_api_key", "Removed for scurity" },
    { "product", "Test" },
    { "component", "Test Component" },
    { "version", "unspecified" },
    { "summary", "Basic API Test" },
    { "description", "A basic API test" }
};

string Json = JsonConvert.SerializeObject(BugData, Formatting.Indented);

var content = new StringContent(Json, Encoding.UTF8, "application/json");
content.Headers.Add("Accept", "application/json");

var Response = await Client.PostAsync("http://bugzillaaddress/rest/bug", content);