Trying to get a .net core 2.0 web api HttpPost method to work with xml input.
Expected Result: When the test endpoint is called from Postman, the input parameter (xmlMessage in the below code) should have the value being sent from the Postman HttpPost body.
Actual Result: input parameter is null.
In startup.cs of the web api project, we have the following code:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddXmlDataContractSerializerFormatters();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
}
In controller:
[HttpPost, Route("test")]
public async Task<IActionResult> Test([FromBody] XMLMessage xmlMessage)
{
return null; //not interested in the result for now
}
XMLMessage class:
[DataContract]
public class XMLMessage
{
public XMLMessage()
{
}
[DataMember]
public string MessageId { get; set; }
}
In Postman Headers:
Content-Type:application/xml
Http Post Body:
<XMLMessage>
<MessageId>testId</MessageId>
</XMLMessage>
Appreciate any help that could point me in the right direction. Thanks in advance..
XMLMessageclass, try using theXElementto receive the XML and then write code along the lines of this answer to ensure you've configured theDataContractannotation correctly. It may be that Web API isn't able to match the class type to the incoming XML.xmlns="http://schemas.datacontract.org/2004/07/MyWebApi.Controllers" SerializationException: Error in line 1 position 13. Expecting element XMLMessage from namespace http://schemas.datacontract.org/2004/07/MyWebApi.Controllers.. Encountered Element with name XMLMessage, namespace .Once I added the namespace like:<XMLMessage xmlns="http://schemas.datacontract.org/2004/07/MyWebApi.Controllers">, it started working. Thanks a lot.