RestSharp似乎不允许我覆盖发布请求的Content-Type.我按照
here发现的指示无效.我还尝试通过request.AddHeaders(“content-type”,“application / json”)手动将标题内容类型设置为application / json;
请求执行的示例:@H_502_3@
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请求原始数据:@H_502_3@
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.有任何想法吗? (提前致谢)@H_502_3@
解决方法
看来这是对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:@H_502_3@
var key = "12345"; var request = new RestRequest("api?key=" + key); // or var request = new RestRequest("api?key={key}); request.AddUrlSegment("key","12345");
我修改的现在运行的Execute请求方法如下所示:@H_502_3@
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); }