0

My C# .NET Web API (v4.7.2) application currently has a request body called with xmlns attribute, but another new users sends request to the same endpoint without any attributes. I use System.Xml.Serialization. I tried many times, but I couldn't build a structure to run both at the same time. Can we do this too? If not, do you have any other suggestions?

Sample 1:

<YourModel>
  <Person>
    <FirstName>John</FirstName>
    <LastName>Doe</LastName>
    <Age>30</Age>
    <Address>
      <City>New York</City>
      <Street>Main Street</Street>
      <ZipCode>10001</ZipCode>
    </Address>
  </Person>
  <Person>
    <FirstName>Jane</FirstName>
    <LastName>Smith</LastName>
    <Age>28</Age>
    <Address>
      <City>Los Angeles</City>
      <Street>Hollywood Blvd</Street>
      <ZipCode>90001</ZipCode>
    </Address>
  </Person>
</YourModel>

Sample 2:

<YourModel xmlns="http://abcxyz.com">
  <Person>
    <FirstName>John</FirstName>
    <LastName>Doe</LastName>
    <Age>30</Age>
    <Address>
      <City>New York</City>
      <Street>Main Street</Street>
      <ZipCode>10001</ZipCode>
    </Address>
  </Person>
  <Person>
    <FirstName>Jane</FirstName>
    <LastName>Smith</LastName>
    <Age>28</Age>
    <Address>
      <City>Los Angeles</City>
      <Street>Hollywood Blvd</Street>
      <ZipCode>90001</ZipCode>
    </Address>
  </Person>
</YourModel>

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
msertacc
  • 97
  • 1
  • 8
  • Visual Studio has a tool to assist in creating classes from XML. Add a new class to your project then copy your XML to the clipboard (highlight the XML, then press ctrl-C). Then in VS, click _Edit_ => _Paste Special_ => _Paste XML as Classes_. – Tu deschizi eu inchid Jul 22 '23 at 14:57
  • The following may be of interest: https://stackoverflow.com/a/72589790/10024425 – Tu deschizi eu inchid Jul 22 '23 at 14:58
  • No. The namespace is hardcoded in the YourModel class as an attribute : [XmlRoot(ElementName = "YourModel", Namespace = "http://abcxyz.com")] – jdweng Jul 22 '23 at 16:07
  • 1
    Maybe receive it as bare XML, strip the namespace then deserialize it. TBH you should be wary of allowing such a permissive API. The spec is the spec, don't allow users to dictate what should or should not be allowed like that. – Charlieface Jul 22 '23 at 23:09
  • Is it possible that the lacking namespace ` xmlns="http://abcxyz.com"` is defined at a higher level than the body? – Siebe Jongebloed Jul 23 '23 at 12:10
  • Names spaces are overused, poorly understood, and in most cased provide little value (mostly just overhead), so feel free to get rid of them in almost every situation. The only time you need them is when you have some developer that blindly follows "standards". Your spec should require no-namespace to really mess with those guys : ). To your question see https://learn.microsoft.com/en-us/answers/questions/205709/c-xml-without-declaration-and-namespace – William Walseth Jul 24 '23 at 11:50

0 Answers0