سؤال

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;
}
هل كانت مفيدة؟

المحلول

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

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

نصائح أخرى

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
});
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top