如何使用请求主体进行GET

时间:2019-07-30 10:20:48

标签: c# .net rest .net-core restsharp

如何使用GET对请求正文进行RestSharp查询(我将RestSharp v. 106.6.10.NET Core 2.2一起使用)。我可以使用WebClient / Postman等来做到这一点。

这是代码失败的{["A non-empty request body is required."]}

var client = new RestClient("BaseUri");
var request = new RestRequest("URL", Method.GET);
request.AddJsonBody(Body); 
client.Execute(request); // {["A non-empty request body is required."]}

这代表一个valid用例,如果不支持,则很可惜。

更新:将GET请求与正文一起使用的动机是利用具有复杂参数的get请求,这些参数无法很好地编码为查询字符串。我知道人们会序列化他们的json并将它们放入查询字符串中,但考虑到毕竟是允许的用法,我宁愿将其放入请求正文中。

2 个答案:

答案 0 :(得分:1)

根据我的经验AddJsonBody被完全破坏了(多次不对我的模型进行序列化时,只是将诸如MyProject.Models.MyModel之类的内容粘贴到Body中,或者甚至将主体留空)。所以我使用以下内容:

var client = new RestClient("BaseUri");
var request = new RestRequest("URL", Method.GET);
request.AddHeader("Content-Type", "application/json");
string serializedBody = Newtonsoft.Json.JsonConvert.SerializeObject(Body);
request.AddParameter("application/json; charset=utf-8", serializedBody, ParameterType.RequestBody);
client.Execute(request);

更新抱歉,在阅读您的问题时我并不耐心。提供的答案是RestSharp,而不是PostSharp

答案 1 :(得分:0)

我通过使用 reflection (反射)来欺骗 WebRequest ,认为发送带有GET请求的正文是合法的。

1。为身体参数创建模型,

public class SampleBodyModel
{
    public String name{ get; set; }
    public String password{ get; set; }
}
  1. 初始化请求。

    SampleBodyModel sampleRequest = new SampleBodyModel
    {
          name= "name",
          password= "password"
    };
    
    //initialize the API call
    var request = WebRequest.Create("API_END_POINT");
    request.ContentType = "application/json";
    request.Method = "GET";
    var myHttpWebRequest = (HttpWebRequest)request;
    
    // ------- Add these two lines if your using JWT token -------
    myHttpWebRequest.PreAuthenticate = true;
    myHttpWebRequest.Headers.Add("Authorization", "Bearer " + "TOKEN");
    // -----------------------------------------------------------
    
    var type = myHttpWebRequest.GetType();
    var currentMethod = type.GetProperty("CurrentMethod", 
            BindingFlags.NonPublic | BindingFlags.Instance).GetValue(myHttpWebRequest);
    var methodType = currentMethod.GetType();
    methodType.GetField("ContentBodyNotAllowed", BindingFlags.NonPublic | 
             BindingFlags.Instance).SetValue(currentMethod, false);
    
    //Add the Request body
    using (var streamWriter = new 
          StreamWriter(myHttpWebRequest.GetRequestStream()))
    {
    
         streamWriter.Write(Newtonsoft.Json.JsonConvert.SerializeObject(sampleRequest));
    }
    var response = (HttpWebResponse)myHttpWebRequest.GetResponse();
    var responseStream = response.GetResponseStream();
    
    var myStreamReader = new StreamReader(responseStream, Encoding.Default);
    var json = myStreamReader.ReadToEnd();
    
    responseStream.Close();
    response.Close();