3

I am always getting null value for my post action param in my asp.net web api.

This is my action.

[System.Web.Mvc.HttpPost]
        public HttpResponseMessage Add([FromBody]Products id)
        {

            var response = new HttpResponseMessage();
            try
            {
                if (id.ProductsList.Length > 0)
                {
                    response.StatusCode = HttpStatusCode.OK;
                    response.EnsureSuccessStatusCode();
                    response.Content = new StringContent(string.Format("Number of products {0}",id.ProductsList.Length) );
                    Logger.Info(string.Format("Number of products {0}", id.ProductsList.Length));
                }
                response.StatusCode = HttpStatusCode.BadRequest;
            }
            catch (Exception ex)
            {
                response.StatusCode = HttpStatusCode.InternalServerError;
                response.Content = new StringContent("Error occured");
                Logger.Error(ex);
            }
            return response;
        }

This is how I am trying to invoke my api.

var filePath = @"C:\Apps\Eastworks\Lott\boots.xml";
                var xmlDoc = new XmlDocument();
                xmlDoc.Load(filePath);

                var client = new HttpClient();
                MediaTypeFormatter jsonFormatter = new XmlMediaTypeFormatter();

                HttpContent content = new ObjectContent<string>(xmlDoc.OuterXml, jsonFormatter);
                if (content.Headers.Contains("Content-Type"))
                {
                    content.Headers.Remove("Content-Type");
                    content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                }

                var result = client.PostAsync("http://localhost:3103/Products/Add",
                              content)
                   .Result;

Following is my model.

[XmlRoot("products")]
    public class Products
    {
        [XmlElement("product")]
        public Product[] ProductsList { get; set; }
    }

    public class Product
    {
        public Product()
        {
            //default implementation

        }
        [XmlElement("code")]
        public string Code { get; set; }

        [XmlElement("related-product")]
        public RelatedProduct[] RelatedProducts { get; set; }


        [XmlElement("description")]
        public string Description { get; set; }

        // Removed some of the properties.

        [XmlElement("variant")]
        public Variant[] Variants { get; set; }
    }

And this is my xml.

<?xml version="1.0" encoding="UTF-8"?>
<products>
  <product>
    <code>mipacaloha</code>
    <related-product>paisley_blk</related-product>
    <related-product>mipacpolkadot</related-product>

    <description>Classic MiPac silhouette. 30cm (12 inches) wide by 37cm (15 inches) high with a 15cm (6 inches) depth.</description>
    <brand>Mi Pac</brand>
    <style>Backpack</style>
    <model-name>Pocket Prints</model-name>
    <weight>0.4</weight>
    <gender>womens</gender>

    <variant>
      <bag-details />
      <exact-colour>Aloha Sky blue</exact-colour>
      <colour>Blue</colour>
      <pic-url>005872</pic-url>
      <sku>136200</sku>
      <ean>5053466362002</ean>
      <stock>0</stock>
      <price>21.99</price>
    </variant>
    <variant>
      <bag-details />
      <exact-colour>Aloha Purple</exact-colour>
      <colour>Purple</colour>
      <pic-url>mipacaloha</pic-url>
      <sku>121521</sku>
      <ean>5053466215216</ean>
      <stock>6</stock>
      <price>18.99</price>
      <original-price>21.99</original-price>
    </variant>

  </product>
</products>

I am setting XmlSerializer to be used in Application_Start.

var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
            xml.UseXmlSerializer = true;

I had seen lot of posts similar to mine. But I couldn't fix my problem. Please advise me.

Thanks, Naresh

2
  • 3
    The following line is always executed: response.StatusCode = HttpStatusCode.BadRequest;. Also, I see no reason at all to call response.EnsureSuccessStatusCode(); on the Server side... Commented Jul 31, 2013 at 14:06
  • @Liel, thanks for spotting. But actually I am getting null reference exception as the action always receiving null value. Commented Jul 31, 2013 at 14:12

3 Answers 3

1

Are you specifying Web API to use XmlSerializer? By default, it uses DataContractSerializer for binding XML requests.

Sign up to request clarification or add additional context in comments.

3 Comments

I have specified that in my Application_Start.
Okay, I believe your XML and the model are not in sync. Look at <related-product>, for example. What you can do is to construct the model object and let web API serialize that for you from a GET action method and compare that with what you have in boots.xml.
I have tried to deserialize the xml to object using XmlSerializer which was working finr. But as you suggested let me give a try. Thanks.
0

This maybe due to the Content-Type you are setting to x-www-form-urlecoded, which expects body like

name=value&name=value

Try to set content type to xml like this and try.

content.Headers.Add("Content-Type", "application/xml");

1 Comment

thanks for your reply. But I have tried that as well. As I am using XmlMediaTypeFormatter it is already taking content type as 'application/xml'.
0

The name of the parameter is Id It could be that, the controller binder seeks for a value named Id in the request's body.

Try renaming the parameter to products:

public HttpResponseMessage Add([FromBody]Products products)

1 Comment

No luck. Still getting the value as null. Am I using the correct content type and encoding?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.