Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add text to request body in RestSharp

I'm trying to use RestSharp to consume a web service. So far everything's gone very well (cheers to John Sheehan and all contributors!) but I've run into a snag. Say I want to insert XML into the body of my RestRequest in its already serialized form (i.e., as a string). Is there an easy way to do this? It appears the .AddBody() function conducts serialization behinds the scenes, so my string is being turned into <String />.

Any help is greatly appreciated!

EDIT: A sample of my current code was requested. See below --

private T ExecuteRequest<T>(string resource,                             RestSharp.Method httpMethod,                             IEnumerable<Parameter> parameters = null,                             string body = null) where T : new() {     RestClient client = new RestClient(this.BaseURL);     RestRequest req = new RestRequest(resource, httpMethod);      // Add all parameters (and body, if applicable) to the request     req.AddParameter("api_key", this.APIKey);     if (parameters != null)     {         foreach (Parameter p in parameters) req.AddParameter(p);     }      if (!string.IsNullOrEmpty(body)) req.AddBody(body); // <-- ISSUE HERE      RestResponse<T> resp = client.Execute<T>(req);     return resp.Data; } 
like image 997
Matt G. Avatar asked Feb 23 '11 18:02

Matt G.


People also ask

How do you add parameters in RestSharp?

var client = new RestClient("http://localhost"); var request = new RestRequest("resource", Method. POST); request. AddParameter("auth_token", "1234"); request. AddBody(json); var response = client.

How pass JSON body in rest Sharp?

AddHeader("Content-Type", "application/json; CHARSET=UTF-8"); request. AddJsonBody(jsonString); var response = client. Execute(request); Console. WriteLine(response.

Is RestSharp a framework?

RestSharp is a C# library used to build and send API requests, and interpret the responses. It is used as part of the C#Bot API testing framework to build the requests, send them to the server, and interpret the responses so assertions can be made.


2 Answers

Here is how to add plain xml string to the request body:

req.AddParameter("text/xml", body, ParameterType.RequestBody);

like image 70
dmitreyg Avatar answered Oct 09 '22 10:10

dmitreyg


To Add to @dmitreyg's answer and per @jrahhali's comment to his answer, in the current version, as of the time this is posted it is v105.2.3, the syntax is as follows:

request.Parameters.Add(new Parameter() {      ContentType = "application/json",      Name = "JSONPAYLOAD", // not required      Type = ParameterType.RequestBody,      Value = jsonBody });  request.Parameters.Add(new Parameter() {      ContentType = "text/xml",      Name = "XMLPAYLOAD", // not required      Type = ParameterType.RequestBody,      Value = xmlBody }); 
like image 39
interesting-name-here Avatar answered Oct 09 '22 10:10

interesting-name-here