繁体   English   中英

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

[英]RestSharp defaulting Content-Type to application/x-www-form-urlencoded on POST

RestSharp似乎不允许我覆盖发布请求的Content-Type。 我按照这里找到的指示无效。 我还尝试通过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。 有任何想法吗? (提前致谢)

看来这是对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);
}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM