Mark Bonafe
Mark Bonafe

Reputation: 1493

Receiving XML in HttpPost Using C#

I thought this would be pretty easy, but it's just not - at least for me. I am trying to send an XML string to a REST endpoint. At this time, the only thing the endpoint has to do is log the XML to a file or database. The XML itself is unknown, it could be literally any length and have any number of nodes. So it really needs to be treated as a string.

My problem is that I cannot determine how to receive the XML/string in the Post method. I am using the RestSharp library.

Here is the Post method I am using; very simple. I removed logging code and try/catch code to keep it simple.

[HttpPost]
public IHttpActionResult Post([FromBody] string status)
{
    // Log the post into the DB
    LogPost(status);
}

The code to perform the post:

public void TestPost()
{
    IRestResponse response;
    try
    {
        // Get the base url for 
        var url = @"http://blahblah/status";
        // Create the XML content
        object xmlContent = "<XML><test><name>Mark</name></test></XML>";
        var client = new RestClient(url);
        var request = new RestRequest(Method.POST);
        // Add required headers
        request.AddHeader("Content-Type", "text/plain");
        request.AddHeader("cache-control", "no-cache");
        request.AddJsonBody(xmlContent);
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        response = client.Execute(request);
    }
    catch (Exception ex)
    {
       ...
    }
}

The problem: the status parameter received by the post is, simply, "Mark". The full XML is missing! I need the entire XML string.

I have tried a few different variations of this. Changing the content-type to "application/xml", "application/json", etc. Nothing is working.

I have tried using request.AddXmlBody(statusObject), and request.AddBody(statusObject). Both were unsuccessful.

I have even tried sending the XML using request.AddHeader() with no luck. What am I missing. There must be something obvious that I'm not getting.

Upvotes: 1

Views: 2368

Answers (2)

Mate
Mate

Reputation: 5284

a) you must configure Web API to use XmlSerializer in your WebApiConfig.Register. Otherwise Web API uses the DataContractSerializer by default.

File: App_Start\WebApiConfig.cs

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Formatters.XmlFormatter.UseXmlSerializer = true; //HERE!
        ...
    }

b) you need to define a class for your xml

    public class test { public string name { get; set; } } //BASED ON YOUR XML NODE

    [HttpPost]
    public IHttpActionResult Post([FromBody] string status)
    {

    }

c) if you need to work with a simple string, change POST method

    public void Post(HttpRequestMessage request)
    {
        string body = request.Content.ReadAsStringAsync().Result;

    }

d) invoke from restsharp client

            string xmlContent = "<test><name>Mark</name></test>"; 
            var client = new RestClient(url);
            var request = new RestRequest(Method.POST);
            request.AddParameter("application/xml", xmlContent, ParameterType.RequestBody); 
            var response = client.Execute(request);

For "some" reason request.AddParameter takes the first param as ContentType(not the Name) https://github.com/restsharp/RestSharp/issues/901

Upvotes: 3

Csaba Benko
Csaba Benko

Reputation: 1161

Did you tried to send the request with

Content-Type: application/xml; charset="utf-8"

instead of text\plain?

Upvotes: 0

Related Questions