AspNet WebApi POST parameter is null when sending XML

前端 未结 2 840
被撕碎了的回忆
被撕碎了的回忆 2020-12-14 08:01

I have a web api service originally using beta bits which I\'ve rebuilt using the release candidate bits and I\'m now having this problem.

I have a POST action that

相关标签:
2条回答
  • 2020-12-14 08:10

    By adding the following lines to the ApplicationStart() method in your Global.asax.cs, your original XML request should work:

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

    By default, the Web API uses the DataContractSerializer class, which requires extra information in the XML request.

    The XmlSerializer seems to work more smoothly for me, since I don't have to add the model's namepsace to each XML request.

    Once again, i found my information in Mike Wasson's article: http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization#xml_media_type_formatter

    0 讨论(0)
  • 2020-12-14 08:30

    I was having the same problem as you, and found the solution by serializing the object using the XmlMediaTypeFormatter as described here: http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization#testing_object_serialization. I used the code in the "Testing Object Serialization" section at the bottom of the article, and replaced his Person object with my model.

    When I serialized my object, I noticed that the following attributes were added to the root node:

    xmlns:i="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns="http://schemas.datacontract.org/2004/07/NAMESPACE.OF.YOUR.MODEL"
    

    If you add these attributes to your xml like so, your controller should correctly serialize the requestValues object:

    <AimiRequest xmlns:i="http://www.w3.org/2001/XMLSchema-instance" 
      xmlns="http://schemas.datacontract.org/2004/07/NAMESPACE.OF.YOUR.MODEL">
      <ContentType />
      <RuleTypes />
      <Metadata>
        <MetadataQueryParameter>
          <Name>ClientName</Name>
          <Value>Client One</Value>
        </MetadataQueryParameter>
        <MetadataQueryParameter>
          <Name>ClientName</Name>
          <Value>Client Two</Value>
        </MetadataQueryParameter>
      </Metadata>
    </AimiRequest>
    
    0 讨论(0)
提交回复
热议问题