How to add text to request body in RestSharp

.NetXmlRestsharp

.Net Problem Overview


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;
}

.Net Solutions


Solution 1 - .Net

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

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

Solution 2 - .Net

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
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatt G.View Question on Stackoverflow
Solution 1 - .NetdmitreygView Answer on Stackoverflow
Solution 2 - .Netinteresting-name-hereView Answer on Stackoverflow