c# - 带有 xml 输入的 .net core 2.0 Web api httppost 为 null

标签 c# .net asp.net-core-2.0 asp.net-core-webapi

尝试获取 .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();
   }
}

在 Controller 中:

[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; }
}

在 postman 标题中:

Content-Type:application/xml

HTTP 帖子正文:

<XMLMessage>
  <MessageId>testId</MessageId>
</XMLMessage>

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

最佳答案

您应该使用 XmlRoot/XmlElement 而不是 DataContract/DataElement 注释类型。以下是要使其正常工作应更改的内容。

在 Startup.cs 上

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

XMLMessage 类:

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

其他部分看起来不错( Controller 和 header )。

Michał Białecki 创建了一篇关于该主题的非常好的帖子。更详细的实现请引用: Accept XML request in ASP.Net MVC Controller

关于c# - 带有 xml 输入的 .net core 2.0 Web api httppost 为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51480259/

相关文章:

c# - 检查对象是否是 T 的子类的扩展方法

c# - SQL CLR UDT 的 ToString() 给出了一个奇怪的结果

asp.net-mvc - 过滤器后的 asp.net 核心验证

asp.net-core-2.0 - ASP.NET Core 2.0 ==> Swapping to Development environment 将显示有关发生的错误的更多详细信息

c# - 如何使用 IAccessible 在 Firefox 中访问文档的 HTML

c# - 如何仅在同一用户的登录 session 中使用 WCF NetNamedPipesBinding 进行进程间通信?

c# - 覆盖 Dictionary.Add

mysql - 从数据库.net core 2中选择特定行

c# - Microsoft JScript 运行时错误 : Object expected thrown when called from codebehind

c# - 基于JSON的架构,如何最好地同步前后端