简体   繁体   English

ASP.Net web api post action param总是无效

[英]ASP.Net web api post action param always coming null

I am always getting null value for my post action param in my asp.net web api. 在我的asp.net web api中,我总是为我的post action param获取null值。

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. 这就是我试图调用我的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。

<?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. 我正在设置要在Application_Start中使用的XmlSerializer。

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 谢谢,Naresh

Are you specifying Web API to use XmlSerializer? 您是否指定Web API以使用XmlSerializer? By default, it uses DataContractSerializer for binding XML requests. 默认情况下,它使用DataContractSerializer来绑定XML请求。

This maybe due to the Content-Type you are setting to x-www-form-urlecoded, which expects body like 这可能是由于你设置为x-www-form-urlecoded的Content-Type,它需要像body一样

name=value&name=value

Try to set content type to xml like this and try. 尝试将内容类型设置为xml,然后尝试。

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

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. 参数的名称是Id可能是,控制器绑定器在请求的主体中寻找名为Id的值。

Try renaming the parameter to products : 尝试将参数重命名为products

public HttpResponseMessage Add([FromBody]Products products)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM