简体   繁体   中英

C# RestSharp No Response From Get With Json Body

My goal is to download a file with a RestSharp GET by passing along a Json body and a security token in the header. For now, I'm just trying to get a response.

I got this code from Postman, where the GET is working (I am prompted where to save the file).

var client = new RestClient(url);
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("Authorization", token);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", json, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);

string responseMsg = "";
if (response.Content == "") 
    responseMsg = response.ErrorMessage
else
    responseMsg = response.Content
return responseMsg;

The only response that I'm getting is the ErrorException " HTTP verb GET does not support body ".

So I believe there is an issue with my logic, not my Json or token. Does anything in my code look incorrect?

Application framework: .Net 4.8

RestSharp version: 106.15.0

Thanks.

Edit:

As mentioned below, a GET request with a body parameter is invalid. After removing the the json body, the request is now working.

var client = new RestClient(url);
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("Authorization", token);
IRestResponse response = client.Execute(request);

In the case of my application, the unique identifier was appended to the endpoint, so only the security token was needed as a header.

GET requests cannot have bodies , or rather, they can, but that behaviour is not defined and so some implementations will reject the request entirely. It appears that RestSharp also intentionally does not support GET requests with bodies for the same reason. According to that thread, .NET itself may support them, so you might wish to try that if it's absolutely necessary.

Whether or not you should do that might come under the umbrella of personal opinion, however with that in mind I would caution against doing things outside of the specification, because any updates to libraries or frameworks have no guarantee of consistency of behaviour when they're being used out of spec. If this is an API you have control over, you should consider bringing it in-spec. If it's not, you should consider contacting the developer to have them look into it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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