2

How to post a Request to Web API as Xml?

I'm using the below test:

[TestMethod]
        public void Should_post_successfully_with_valid_userDetailsList_usingRestSharp()
        {
            // arrange
            string url = string.Format("{0}/User/BulkLoad", this._baseUrlForLuis);

            var client = new RestClient(url);

            var request = new RestRequest(Method.POST)
                {
                    RequestFormat = DataFormat.Xml
                };

            request.AddBody("<user></user>");

             request.AddHeader("Accept", "application/xml");

            // act
            IRestResponse response = client.Execute<HttpResponseMessage>(request);

            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
        }

and my action looks like below; it accepts a string:

        [HttpPost]
        public HttpResponseMessage BulkLoad([FromBody] string userDetailsListXml)
        {
}

But userDetailsListXml is always null so the value is not passed over.

How to fix it?

I tried with Ajax Post and the below code gets passed and works fine:

$.post("http://www.domain.com/User/BulkLoad", {"" : "<user></user>"});

But how to make it work with RestSharp?

1 Answer 1

1
var personString = "<Person><Name>Person Name</Name></Person>"; // Your XML string

var restClient = new RestClient("http://localhost:56453/api/people");

var restRequest = new RestRequest("Post", Method.POST);

restRequest.RequestFormat = DataFormat.Xml;
restRequest.AddParameter("application/xml", personString, ParameterType.RequestBody);
var response = restClient.Execute(restRequest);

Don't forget to add folloing code in WebApiConfig.cs

config.Formatters.XmlFormatter.UseXmlSerializer = true;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.