加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – RestSharp在POST上将内容类型默认为application / x-www-f

发布时间:2020-12-15 08:34:25 所属栏目:百科 来源:网络整理
导读:RestSharp似乎不允许我覆盖发布请求的Content-Type.我按照 here发现的指示无效.我还尝试通过request.AddHeaders(“content-type”,“application / json”)手动将标题内容类型设置为application / json; 请求执行的示例: private IRestResponse ExecuteRequ
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.有任何想法吗? (提前致谢)

解决方法

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

If it’s a GET request,you can’t have a request body and AddParameter
adds values to the URL querystring. If it’s a POST you can’t include a
POST parameter and a serialized request body since they occupy the
same space. You could do a multipart POST body but this is not very
common. Unfortunately if you’re making a POST the only way to set the
URL querystring value is through either string concatenation or
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",ParameterType.RequestBody);

    return client.Execute(request);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读