king jia
king jia

Reputation: 712

C# Post XML file using RestSharp

I have written a method to post messages to an uri.

public string RestClientPost(string uri, string message = null)
    {
        var client = new RestClient(uri);
        var request = new RestRequest(Method.POST);
        request.AddHeader("Accept", "text/xml");
        if (!string.IsNullOrEmpty(message))
            request.AddParameter(message, ParameterType.RequestBody);

        var result = "";
        var response = client.Execute(request);

        if (response.StatusCode == HttpStatusCode.OK)
        {
            result = response.Content;
            Console.WriteLine(result);
        }
        else
        {
            result = response.StatusCode.ToString();
        }


        return result;
    }

and below code is used above method to post.

public void test123()
    {
        string uri = "myuri"; //private uri, cannot expose.
        var file= System.IO.File.ReadAllText(Path.Combine(Settings.EnvValPath, "RestClientXML", "test.XML"));
        var content = new RestClientServices().RestClientPost(uri, file);

    }

however, it returns "Unsupported Media type".

my test.XML's content is

<customer> 
    <customerName>test</customerName > 
    <customerStatus>OK</customerStatus > 
</customer>

And using Advanced Rest Client Plugin for Google Chrome, I'm able to post it and return with string that I wanted. Is there something wrong?? I set "content-type" to "text/xml" in Advanced Rest Client.

Upvotes: 2

Views: 5843

Answers (2)

saber tabatabaee yazdi
saber tabatabaee yazdi

Reputation: 4959

im using postman,

postman get the c# code tools

if you can call any xml web services with this tools , then you can click on code and select restsharp and copy paste it to your code

Upvotes: 1

Jose Rodriguez
Jose Rodriguez

Reputation: 10162

This happened because the header "Accept" is to specify a type of return object. In this case a value of a variable content, not the type of content to send. Specify a type of content to send with: "Content-Type: application/xml".

If a return type of POST request is a media file, you can use 'image/png' or 'image/jpeg'. You can use multiple accept header values like: "application/xml, application/xhtml+xml, and image/png". For example, you can use Fiddler to debug HTTP(s) traffic - it's a good tool for web developers.

Upvotes: 0

Related Questions