title: How can we pass XML as request to .Net core API and get response in XML from Same API in c#?
body: <p>I want to create an API in <code>.net core</code> which accept <code>XML</code> request and gives response in XML only.</p>
  
  <p>I have searched and created sample but when I hit request to the <code>API</code> with <code>XML</code> request it does not work. </p>
  
  <blockquote>
    <p>Debugger did not come up to the controller.</p>
  </blockquote>
  
  <p>I have also added below the line of code in the configure services of the <code>startup.cs class</code>.</p>
  
  <pre><code> services.AddMvc(options =&gt;
          {
              options.RespectBrowserAcceptHeader = true; // false by default
              options.InputFormatters.Insert(0, new XDocumentInputFormatter());
          }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
             .AddXmlSerializerFormatters()
            .AddXmlDataContractSerializerFormatters();
  
  </code></pre>
  
  <p>The <code>POST</code> method have written in the controller as below.</p>
  
  <pre><code>
      [Produces("application/xml")]
              [ProducesResponseType(typeof(CustomerDetails), (int)HttpStatusCode.OK)]
              [HttpPost("CustomerDetails", Name = "CustomerDetails")]
              public IActionResult CustomerDetails([FromBody] CustomerDetails CustReq)
              {
                  var resp = new CustomerDetails
                  {
                     BankId="1234567"
                  };
                  return Ok(resp);
              }
  
  </code></pre>
  
  <p>Processing my request from Postman getting an error.
  An unhandled exception occurred while processing the request.
  InvalidCastException: Unable to cast object of type 'System.Xml.Linq.XDocument' to type 'CustomerValidationAPI.Models.CustomerDetails'.</p>
  
  <p>Below is my <code>XML</code> request I want to process. </p>
  
  <p>It also has multiple nodes how can we handle.</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
      &lt;FIXML xmlns="http://www.finacle.com/fixml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.finacle.com/fixml
  executeFinacleScript.xsd"&gt;
         &lt;Header&gt;
            &lt;RequestHeader&gt;
               &lt;MessageKey&gt;
                  &lt;RequestUUID&gt;FEBA_1553756445880&lt;/RequestUUID&gt;
                  &lt;ServiceRequestId&gt;executeFinacleScript&lt;/ServiceRequestId&gt;
                  &lt;ServiceRequestVersion&gt;10.2&lt;/ServiceRequestVersion&gt;
                  &lt;ChannelId&gt;COR&lt;/ChannelId&gt;
               &lt;/MessageKey&gt;
               &lt;RequestMessageInfo&gt;
                  &lt;BankId&gt;04&lt;/BankId&gt;
                  &lt;TimeZone&gt;GMT+05:00&lt;/TimeZone&gt;
                  &lt;EntityId /&gt;
                  &lt;EntityType /&gt;
                  &lt;ArmCorrelationId /&gt;
                  &lt;MessageDateTime&gt;2019-03-28T11:00:45.880&lt;/MessageDateTime&gt;
               &lt;/RequestMessageInfo&gt;
               &lt;Security&gt;
                  &lt;Token&gt;
                     &lt;PasswordToken&gt;
                        &lt;UserId&gt;11111&lt;/UserId&gt;
                        &lt;Password /&gt;
                     &lt;/PasswordToken&gt;
                  &lt;/Token&gt;
                  &lt;FICertToken /&gt;
                  &lt;RealUserLoginSessionId /&gt;
                  &lt;RealUser /&gt;
                  &lt;RealUserPwd /&gt;
                  &lt;SSOTransferToken /&gt;
               &lt;/Security&gt;
            &lt;/RequestHeader&gt;
         &lt;/Header&gt;
         &lt;Body&gt;
            &lt;executeFinacleScriptRequest&gt;
               &lt;ExecuteFinacleScriptInputVO&gt;
                  &lt;requestId&gt;validateAcct.scr&lt;/requestId&gt;
               &lt;/ExecuteFinacleScriptInputVO&gt;
               &lt;executeFinacleScript_CustomData&gt;
                  &lt;ACCT_NUM&gt;01122507576&lt;/ACCT_NUM&gt;
                  &lt;PHONE_NUM&gt;59887834&lt;/PHONE_NUM&gt;
                  &lt;NIC&gt;G2105493001653&lt;/NIC&gt;
               &lt;/executeFinacleScript_CustomData&gt;
            &lt;/executeFinacleScriptRequest&gt;
         &lt;/Body&gt;
      &lt;/FIXML&gt;
  </code></pre>
  
  <p>Customer Details Model Have created as below</p>
  
  <pre><code> public class CustomerDetails
      {
          [Required]
          public string RequestUUID { get; set; }
          [Required]
          public string ServiceRequestId { get; set; }
          [Required]
          public string ServiceRequestVersion { get; set; }
          [Required]
          public string ChannelId { get; set; }
          [Required]
          public string BankId { get; set; }
          [Required]
          public string TimeZone { get; set; }
  
          public string EntityId { get; set; }
  
          public string EntityType { get; set; }
  
          public string ArmCorrelationId { get; set; }
  
          [Required]
          [DataType(DataType.Date)]
          public DateTime MessageDateTime { get; set; }
  
          [Required]
          public string Password { get; set; }
          public string FICertToken { get; set; }
          public string RealUserLoginSessionId { get; set; }
          public string RealUser { get; set; }
          public string RealUserPwd { get; set; }
          public string SSOTransferToken { get; set; }
  
          [Required]
          public string requestId { get; set; }
          [Required]
          public string ACCT_NUM { get; set; }
          [Required]
          public string PHONE_NUM { get; set; }
          [Required]
          public string NIC { get; set; }
      } 
  </code></pre>
  
  <pre><code>
  My startUp class 
  
      public void ConfigureServices(IServiceCollection services)
      {
          services.AddMvc(options =&gt;
          {
              options.RespectBrowserAcceptHeader = true; // false by default
              options.InputFormatters.Insert(0, new XDocumentInputFormatter());
          }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
             .AddXmlSerializerFormatters()
            .AddXmlDataContractSerializerFormatters();
      } 
  
  XDocumentInputFormatter in class have taken as below.. 
  
       public class XDocumentInputFormatter : InputFormatter, IInputFormatter, IApiRequestFormatMetadataProvider
          {
              public XDocumentInputFormatter()
              {
                  SupportedMediaTypes.Add("application/xml");
              }
  
              protected override bool CanReadType(Type type)
              {
                  if (type.IsAssignableFrom(typeof(XDocument))) return true;
                  return base.CanReadType(type);
              }
  
              //public override async Task&lt;InputFormatterResult&gt; ReadRequestBodyAsync(InputFormatterContext context)
              //{
              //    var xmlDoc = await XDocument.LoadAsync(context.HttpContext.Request.Body, LoadOptions.None, CancellationToken.None);
              //    return InputFormatterResult.Success(xmlDoc);
              //}
  
              public override async Task&lt;InputFormatterResult&gt; ReadRequestBodyAsync(InputFormatterContext context)
              {
                  // Use StreamReader to convert any encoding to UTF-16 (default C# and sql Server).
                  using (var streamReader = new StreamReader(context.HttpContext.Request.Body))
                  {
                      var xmlDoc = await XDocument.LoadAsync(streamReader, LoadOptions.None, CancellationToken.None);
                      return InputFormatterResult.Success(xmlDoc);
                  }
              }
          }
  
  </code></pre>
  
  <p>ERROR I AM GETTING NOW </p>
  
  <p>An unhandled exception occurred while processing the request.
  InvalidOperationException: http://www.finacle.com/fixml'> was not expected.</p>
  
  <p>Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderTestClass.Read3_TestClass()
  InvalidOperationException: There is an error in XML document (1, 174).</p>
  
  <p>System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, string encodingStyle, XmlDeserializationEvents events)</p>
  
  <pre><code>Created the Class from XML as below
  
   public class XMLClass
      {
  
          // NOTE: Generated code may require at least .NET Framework 4.5 or .NET Core/Standard 2.0.
          /// &lt;remarks/&gt;
          [System.SerializableAttribute()]
          [System.ComponentModel.DesignerCategoryAttribute("code")]
          [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.finacle.com/fixml")]
          [System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.finacle.com/fixml", IsNullable = false)]
          public partial class FIXML
          {
  
              private FIXMLHeader headerField;
  
              private FIXMLBody bodyField;
  
              /// &lt;remarks/&gt;
              public FIXMLHeader Header
              {
                  get
                  {
                      return this.headerField;
                  }
                  set
                  {
                      this.headerField = value;
                  }
              }
  
              /// &lt;remarks/&gt;
              public FIXMLBody Body
              {
                  get
                  {
                      return this.bodyField;
                  }
                  set
                  {
                      this.bodyField = value;
                  }
              }
          }
  
          /// &lt;remarks/&gt;
          [System.SerializableAttribute()]
          [System.ComponentModel.DesignerCategoryAttribute("code")]
          [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.finacle.com/fixml")]
          public partial class FIXMLHeader
          {
  
              private FIXMLHeaderRequestHeader requestHeaderField;
  
              /// &lt;remarks/&gt;
              public FIXMLHeaderRequestHeader RequestHeader
              {
                  get
                  {
                      return this.requestHeaderField;
                  }
                  set
                  {
                      this.requestHeaderField = value;
                  }
              }
          }
  
          /// &lt;remarks/&gt;
          [System.SerializableAttribute()]
          [System.ComponentModel.DesignerCategoryAttribute("code")]
          [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.finacle.com/fixml")]
          public partial class FIXMLHeaderRequestHeader
          {
  
              private FIXMLHeaderRequestHeaderMessageKey messageKeyField;
  
              private FIXMLHeaderRequestHeaderRequestMessageInfo requestMessageInfoField;
  
              private FIXMLHeaderRequestHeaderSecurity securityField;
  
              /// &lt;remarks/&gt;
              public FIXMLHeaderRequestHeaderMessageKey MessageKey
              {
                  get
                  {
                      return this.messageKeyField;
                  }
                  set
                  {
                      this.messageKeyField = value;
                  }
              }
  
              /// &lt;remarks/&gt;
              public FIXMLHeaderRequestHeaderRequestMessageInfo RequestMessageInfo
              {
                  get
                  {
                      return this.requestMessageInfoField;
                  }
                  set
                  {
                      this.requestMessageInfoField = value;
                  }
              }
  
              /// &lt;remarks/&gt;
              public FIXMLHeaderRequestHeaderSecurity Security
              {
                  get
                  {
                      return this.securityField;
                  }
                  set
                  {
                      this.securityField = value;
                  }
              }
          }
  
          /// &lt;remarks/&gt;
          [System.SerializableAttribute()]
          [System.ComponentModel.DesignerCategoryAttribute("code")]
          [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.finacle.com/fixml")]
          public partial class FIXMLHeaderRequestHeaderMessageKey
          {
  
              private string requestUUIDField;
  
              private string serviceRequestIdField;
  
              private decimal serviceRequestVersionField;
  
              private string channelIdField;
  
              /// &lt;remarks/&gt;
              public string RequestUUID
              {
                  get
                  {
                      return this.requestUUIDField;
                  }
                  set
                  {
                      this.requestUUIDField = value;
                  }
              }
  
              /// &lt;remarks/&gt;
              public string ServiceRequestId
              {
                  get
                  {
                      return this.serviceRequestIdField;
                  }
                  set
                  {
                      this.serviceRequestIdField = value;
                  }
              }
  
              /// &lt;remarks/&gt;
              public decimal ServiceRequestVersion
              {
                  get
                  {
                      return this.serviceRequestVersionField;
                  }
                  set
                  {
                      this.serviceRequestVersionField = value;
                  }
              }
  
              /// &lt;remarks/&gt;
              public string ChannelId
              {
                  get
                  {
                      return this.channelIdField;
                  }
                  set
                  {
                      this.channelIdField = value;
                  }
              }
          }
  
          /// &lt;remarks/&gt;
          [System.SerializableAttribute()]
          [System.ComponentModel.DesignerCategoryAttribute("code")]
          [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.finacle.com/fixml")]
          public partial class FIXMLHeaderRequestHeaderRequestMessageInfo
          {
  
              private byte bankIdField;
  
              private string timeZoneField;
  
              private object entityIdField;
  
              private object entityTypeField;
  
              private object armCorrelationIdField;
  
              private System.DateTime messageDateTimeField;
  
              /// &lt;remarks/&gt;
              public byte BankId
              {
                  get
                  {
                      return this.bankIdField;
                  }
                  set
                  {
                      this.bankIdField = value;
                  }
              }
  
              /// &lt;remarks/&gt;
              public string TimeZone
              {
                  get
                  {
                      return this.timeZoneField;
                  }
                  set
                  {
                      this.timeZoneField = value;
                  }
              }
  
              /// &lt;remarks/&gt;
              public object EntityId
              {
                  get
                  {
                      return this.entityIdField;
                  }
                  set
                  {
                      this.entityIdField = value;
                  }
              }
  
              /// &lt;remarks/&gt;
              public object EntityType
              {
                  get
                  {
                      return this.entityTypeField;
                  }
                  set
                  {
                      this.entityTypeField = value;
                  }
              }
  
              /// &lt;remarks/&gt;
              public object ArmCorrelationId
              {
                  get
                  {
                      return this.armCorrelationIdField;
                  }
                  set
                  {
                      this.armCorrelationIdField = value;
                  }
              }
  
              /// &lt;remarks/&gt;
              public System.DateTime MessageDateTime
              {
                  get
                  {
                      return this.messageDateTimeField;
                  }
                  set
                  {
                      this.messageDateTimeField = value;
                  }
              }
          }
  
          /// &lt;remarks/&gt;
          [System.SerializableAttribute()]
          [System.ComponentModel.DesignerCategoryAttribute("code")]
          [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.finacle.com/fixml")]
          public partial class FIXMLHeaderRequestHeaderSecurity
          {
  
              private FIXMLHeaderRequestHeaderSecurityToken tokenField;
  
              private object fICertTokenField;
  
              private object realUserLoginSessionIdField;
  
              private object realUserField;
  
              private object realUserPwdField;
  
              private object sSOTransferTokenField;
  
              /// &lt;remarks/&gt;
              public FIXMLHeaderRequestHeaderSecurityToken Token
              {
                  get
                  {
                      return this.tokenField;
                  }
                  set
                  {
                      this.tokenField = value;
                  }
              }
  
              /// &lt;remarks/&gt;
              public object FICertToken
              {
                  get
                  {
                      return this.fICertTokenField;
                  }
                  set
                  {
                      this.fICertTokenField = value;
                  }
              }
  
              /// &lt;remarks/&gt;
              public object RealUserLoginSessionId
              {
                  get
                  {
                      return this.realUserLoginSessionIdField;
                  }
                  set
                  {
                      this.realUserLoginSessionIdField = value;
                  }
              }
  
              /// &lt;remarks/&gt;
              public object RealUser
              {
                  get
                  {
                      return this.realUserField;
                  }
                  set
                  {
                      this.realUserField = value;
                  }
              }
  
              /// &lt;remarks/&gt;
              public object RealUserPwd
              {
                  get
                  {
                      return this.realUserPwdField;
                  }
                  set
                  {
                      this.realUserPwdField = value;
                  }
              }
  
              /// &lt;remarks/&gt;
              public object SSOTransferToken
              {
                  get
                  {
                      return this.sSOTransferTokenField;
                  }
                  set
                  {
                      this.sSOTransferTokenField = value;
                  }
              }
          }
  
          /// &lt;remarks/&gt;
          [System.SerializableAttribute()]
          [System.ComponentModel.DesignerCategoryAttribute("code")]
          [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.finacle.com/fixml")]
          public partial class FIXMLHeaderRequestHeaderSecurityToken
          {
  
              private FIXMLHeaderRequestHeaderSecurityTokenPasswordToken passwordTokenField;
  
              /// &lt;remarks/&gt;
              public FIXMLHeaderRequestHeaderSecurityTokenPasswordToken PasswordToken
              {
                  get
                  {
                      return this.passwordTokenField;
                  }
                  set
                  {
                      this.passwordTokenField = value;
                  }
              }
          }
  
          /// &lt;remarks/&gt;
          [System.SerializableAttribute()]
          [System.ComponentModel.DesignerCategoryAttribute("code")]
          [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.finacle.com/fixml")]
          public partial class FIXMLHeaderRequestHeaderSecurityTokenPasswordToken
          {
  
              private ushort userIdField;
  
              private object passwordField;
  
              /// &lt;remarks/&gt;
              public ushort UserId
              {
                  get
                  {
                      return this.userIdField;
                  }
                  set
                  {
                      this.userIdField = value;
                  }
              }
  
              /// &lt;remarks/&gt;
              public object Password
              {
                  get
                  {
                      return this.passwordField;
                  }
                  set
                  {
                      this.passwordField = value;
                  }
              }
          }
  
          /// &lt;remarks/&gt;
          [System.SerializableAttribute()]
          [System.ComponentModel.DesignerCategoryAttribute("code")]
          [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.finacle.com/fixml")]
          public partial class FIXMLBody
          {
  
              private FIXMLBodyExecuteFinacleScriptRequest executeFinacleScriptRequestField;
  
              /// &lt;remarks/&gt;
              public FIXMLBodyExecuteFinacleScriptRequest executeFinacleScriptRequest
              {
                  get
                  {
                      return this.executeFinacleScriptRequestField;
                  }
                  set
                  {
                      this.executeFinacleScriptRequestField = value;
                  }
              }
          }
  
          /// &lt;remarks/&gt;
          [System.SerializableAttribute()]
          [System.ComponentModel.DesignerCategoryAttribute("code")]
          [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.finacle.com/fixml")]
          public partial class FIXMLBodyExecuteFinacleScriptRequest
          {
  
              private FIXMLBodyExecuteFinacleScriptRequestExecuteFinacleScriptInputVO executeFinacleScriptInputVOField;
  
              private FIXMLBodyExecuteFinacleScriptRequestExecuteFinacleScript_CustomData executeFinacleScript_CustomDataField;
  
              /// &lt;remarks/&gt;
              public FIXMLBodyExecuteFinacleScriptRequestExecuteFinacleScriptInputVO ExecuteFinacleScriptInputVO
              {
                  get
                  {
                      return this.executeFinacleScriptInputVOField;
                  }
                  set
                  {
                      this.executeFinacleScriptInputVOField = value;
                  }
              }
  
              /// &lt;remarks/&gt;
              public FIXMLBodyExecuteFinacleScriptRequestExecuteFinacleScript_CustomData executeFinacleScript_CustomData
              {
                  get
                  {
                      return this.executeFinacleScript_CustomDataField;
                  }
                  set
                  {
                      this.executeFinacleScript_CustomDataField = value;
                  }
              }
          }
  
          /// &lt;remarks/&gt;
          [System.SerializableAttribute()]
          [System.ComponentModel.DesignerCategoryAttribute("code")]
          [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.finacle.com/fixml")]
          public partial class FIXMLBodyExecuteFinacleScriptRequestExecuteFinacleScriptInputVO
          {
  
              private string requestIdField;
  
              /// &lt;remarks/&gt;
              public string requestId
              {
                  get
                  {
                      return this.requestIdField;
                  }
                  set
                  {
                      this.requestIdField = value;
                  }
              }
          }
  
          /// &lt;remarks/&gt;
          [System.SerializableAttribute()]
          [System.ComponentModel.DesignerCategoryAttribute("code")]
          [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.finacle.com/fixml")]
          public partial class FIXMLBodyExecuteFinacleScriptRequestExecuteFinacleScript_CustomData
          {
  
              private uint aCCT_NUMField;
  
              private uint pHONE_NUMField;
  
              private string nICField;
  
              /// &lt;remarks/&gt;
              public uint ACCT_NUM
              {
                  get
                  {
                      return this.aCCT_NUMField;
                  }
                  set
                  {
                      this.aCCT_NUMField = value;
                  }
              }
  
              /// &lt;remarks/&gt;
              public uint PHONE_NUM
              {
                  get
                  {
                      return this.pHONE_NUMField;
                  }
                  set
                  {
                      this.pHONE_NUMField = value;
                  }
              }
  
              /// &lt;remarks/&gt;
              public string NIC
              {
                  get
                  {
                      return this.nICField;
                  }
                  set
                  {
                      this.nICField = value;
                  }
              }
          }
  
  
      }
  
  public class Token
  {
     public PasswordToken PasswordToken{get;set;} 
  
  }
  
  public class PasswordToken
  {
     public string UserId{get;set;} 
  
     public string Password{get;set;} 
  
  }
  
  public class Body
  {
     public executeFinacleScriptRequest executeFinacleScriptRequest{get;set;} 
  
  }
  
  public class executeFinacleScriptRequest
  {
     public ExecuteFinacleScriptInputVO ExecuteFinacleScriptInputVO{get;set;} 
  
     public executeFinacleScript_CustomData executeFinacleScript_CustomData{get;set;} 
  
  }
  
  public class ExecuteFinacleScriptInputVO
  {
     public string requestId{get;set;} 
  
  }
  
  public class executeFinacleScript_CustomData
  {
     public string ACCT_NUM{get;set;} 
  
     public string PHONE_NUM{get;set;} 
  
     public string NIC{get;set;} 
  
  }
  
  
  </code></pre>