RestSharp在POST上将Content-Type默认为application / x-www-form-urlencoded

时间:2015-02-15 23:53:19

标签: c# restsharp

RestSharp似乎不允许我覆盖帖子请求的Content-Type。我按照找到的here指示无效。我还尝试通过request.AddHeaders(“content-type”,“application / json”)手动将标题内容类型设置为application / json;

请求执行的示例:

private IRestResponse ExecuteRequest<T>(string resource, Method method, T model)
{
    var client = CreateRestClient();
    var request = new RestRequest(resource, method) 
    { 
        RequestFormat = DataFormat.Json 
    };
    var json = JsonConvert.SerializeObject(model);

    request.AddHeader("Accept", "application/json");
    request.AddHeader("User-Agent", "Fiddler");
    request.Parameters.Clear();
    request.AddParameter("auth_token", _apiKey);
    request.AddParameter("application/json", json, ParameteType.RequestBody);

    return client.Execute(request); 
}

响应错误消息:

{
  "error": {
  "code": 400,
  "message": "The request requires a properly encoded body with the 'content-type' header set to '['application/json']",
  "type": "Bad Request" }
}

Fiddler请求原始数据:

POST  **omitted** HTTP/1.1
Accept: application/json, application/xml, text/json, text/x-json,text/javascript, text/xml
User-Agent: RestSharp/105.0.1.0
Content-Type: application/x-www-form-urlencoded
Host: **omitted**
Content-Length: 51
Accept-Encoding: gzip, deflate
Connection: Keep-Alive

如您所见,请求Content-Type仍然是application / x-www-form-urlencoded。有任何想法吗? (提前谢谢)

2 个答案:

答案 0 :(得分:9)

看来这是对RestSharp如何解释发布请求参数的误解。来自John Sheehan在谷歌小组的帖子:

  

如果是GET请求,则您无法拥有请求正文和AddParameter   将值添加到URL查询字符串。如果是POST,则不能包含   POST参数和序列化的请求体因为它们占用了   同样的空间。你可以做一个多部分POST机构,但这不是很好   共同。不幸的是,如果您正在设置POST,那么设置它的唯一方法就是   URL查询字符串值是通过字符串连接或   UrlSegments:

var key = "12345";
var request = new RestRequest("api?key=" + key);
// or
var request = new RestRequest("api?key={key});
request.AddUrlSegment("key", "12345");

我现在修改的Execute请求方法如下所示:

private IRestResponse ExecuteRequestAsPost<T>(T model, string resource, Method method)
{
    resource += "?auth_token={token}";
    var client = CreateRestClient();
    var request = new RestRequest(resource, method) { RequestFormat = DataFormat.Json };
    var json = JsonConvert.SerializeObject(model);
    request.AddHeader("User-Agent", "Fiddler");

    request.AddUrlSegment("token", _apiKey);
    request.AddParameter("application/json", json, ParameterType.RequestBody);

    return client.Execute(request);
}

答案 1 :(得分:2)

听起来你可能已经弄明白了,但如果你对另一种选择感兴趣,那么我写作Flurl的目标之一就是要明确你想要放置参数的位置,仍然用更少的代码来做。在这种情况下,整个请求看起来像这样:

var response = await baseUrl
    .AppendPathSegment(resource)
    .SetQueryParam("auth_token", _apiKey)
    .WithHeader("User-Agent", "Fiddler")
    .PostJsonAsync(model);