【发布时间】:2016-05-22 22:30:47
【问题描述】:
当我使用 C# 创建客户端时,我很难解决来自 REST api 的错误请求响应。我使用 Fiddler 2 测试了 REST api 并在那里执行它,但是当我以编程方式创建相同的东西时,我得到 400 响应。这是我的 Fiddler 作曲家测试:
网址:
https://<third-party-rest-client>/api/v2/job
这是我的标题
User-Agent: Fiddler
Content-Type: application/json
Accept: application/json
icSessionId: PomCSBCVU4VgXCJ5
Content-Length: 123
这是我发送 POST 请求的正文
{
"@type": "job",
"taskId":"0000G20G000000000002",
"taskName":"TestReplication",
"taskType":"DRS",
"callbackURL":""
}
这个 POST 带有一个 200 响应和一个响应正文,这是完美的,但是当我尝试用这段代码在 C# 中模拟同样的事情时:
public JobResponse RunJob(JobRequest jobRequest)
{
try
{
client = new HttpClient();
client.BaseAddress = new Uri(loggedUser.serverUrl + "/");
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.TryAddWithoutValidation("icSessionId", icSessionId);
string message = JsonConvert.SerializeObject(jobRequest);
message = message.Insert(1, "\"@type\": \"job\",");
Console.WriteLine(message);
var response = client.PostAsJsonAsync("api/v2/job", message).Result;
if (response.IsSuccessStatusCode)
{
return response.Content.ReadAsAsync<JobResponse>().Result;
}
else
{
var result = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(result);
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return null;
}
返回 400。有人知道我的代码有什么问题吗?
【问题讨论】:
-
您从 Console.WriteLines 中得到了什么? 400 的身体又回来了什么?
-
API 是否接受大写 JSON 值? HttpClient 默认发送大写的字段名。
-
你不需要序列化你的对象。您可以将其直接传递给
client.PostAsJsonAsync。此外,在您的loggedUser.serverUrl上是否有类似"http://servername"的内容。您可以在asp.net/web-api/overview/advanced/… 看到一些示例 -
@SimonC - 我得到的 html 看起来像这样:
Error URI: /saas/api /v2/job
状态码:400
另外,api 接受我显示的小写值。您是说 HttpClient 正在将它们更改为大写值?