简体   繁体   中英

.net core 2.0 web api httppost with xml input comes in as null

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..

I was able to make it work. The only thing I had to change was the method Startup.ConfigureServices as follows:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc()
            .AddXmlSerializerFormatters(); 
}

You should be using XmlRoot/XmlElement instead of the DataContract/DataElement annotations types. Below is what should be changed in order to make it work.

On Startup.cs

public void ConfigureServices(IServiceCollection services){
    services.AddMvc(options =>
    {
        options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
    });
    // Add remaining settings
}

XMLMessage class:

[XmlRoot(ElementName = "XMLMessage")]
public class TestClass
{
    //XmlElement not mandatory, since property names are the same
    [XmlElement(ElementName = "MessageId")]
    public string MessageId { get; set; }
}

The other pieces look good (Controller and header).

Michał Białecki created a very nice post about the topic. Please refer to it for more a more detailed implementation: Accept XML request in ASP.Net MVC Controller

Startup.cs

using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace test
{
    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.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(config =>
            {
                config.InputFormatters.Add(new XmlSerializerInputFormatter());
            }).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();
        }
    }
}

Controller.cs

using System.Runtime.Serialization;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace test.Controllers
{
    [DataContract]
    public class TestClass
    {
        [DataMember]
        public string Message { get; set; }
    }

    [Route("[controller]")]
    public class TestController : Controller
    {
        [HttpPost, Route("test")]
        public async Task<IActionResult> Test([FromBody]TestClass test)
        {
            return Ok("OK");
        }

    }

}

Program.cs

using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting;

namespace test
{
    public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .Build();
    }
}

test.csproj

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp2.0</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.9" />
  </ItemGroup>
</Project>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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