带有 xml 输入的 .net core 2.0 web api httppost 为 null

尝试使用 .net core 2.0 web api HttpPost 方法来处理 xml 输入。


预期结果:当从 Postman 调用测试端点时,输入参数(以下代码中的 xmlMessage)应具有从 Postman HttpPost 正文发送的值。


实际结果:输入参数为空。


在web api项目的startup.cs中,我们有如下代码:


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();

   }

}

在控制器中:


[HttpPost, Route("test")]

public async Task<IActionResult> Test([FromBody] XMLMessage xmlMessage)

{

    return null; //not interested in the result for now

}

XMLMessage 类:


[DataContract]

public class XMLMessage

{

    public XMLMessage()

    {

    }


    [DataMember]

    public string MessageId { get; set; }

}

在邮递员标题中:


Content-Type:application/xml

Http 帖子正文:


<XMLMessage>

  <MessageId>testId</MessageId>

</XMLMessage>

感谢任何可以为我指明正确方向的帮助。提前致谢..


慕哥9229398
浏览 208回答 3
3回答

撒科打诨

您应该使用 XmlRoot/XmlElement 而不是 DataContract/DataElement 注释类型。以下是应该更改以使其工作的内容。在启动.cspublic void ConfigureServices(IServiceCollection services){&nbsp; &nbsp; services.AddMvc(options =>&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; options.OutputFormatters.Add(new XmlSerializerOutputFormatter());&nbsp; &nbsp; });&nbsp; &nbsp; // Add remaining settings}XMLMessage 类:[XmlRoot(ElementName = "XMLMessage")]public class TestClass{&nbsp; &nbsp; //XmlElement not mandatory, since property names are the same&nbsp; &nbsp; [XmlElement(ElementName = "MessageId")]&nbsp; &nbsp; public string MessageId { get; set; }}其他部分看起来不错(控制器和标题)。

宝慕林4294392

我能够让它工作。我唯一需要改变的是方法Startup.ConfigureServices如下:public void ConfigureServices(IServiceCollection services){&nbsp; &nbsp; services.AddMvc()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .AddXmlSerializerFormatters();&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP