【问题标题】:C# How to ignore Xml Header in request to WebApi?C#如何在对WebApi的请求中忽略Xml Header?
【发布时间】:2019-03-15 19:09:19
【问题描述】:

我正在为我的 WebApi 创建一个新路由,它应该通过 HTTP POST 接收以下 XML

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<AcquireKeysRequest>
  <version>2</version>
  <content>
    <id>MTV</id>
    <type>VOD</type>
  </content>
  <protection>
    <protection-system>
      <type>DASH-CENC</type>
      <system-id>urn:mpeg:dash:mp4protection:2011</system-id>
    </protection-system>
  </protection>
  <key-timing>
    <position>0</position>
  </key-timing>
</AcquireKeysRequest>

我已经通过框架映射它,使用以下模型:

public class AcquireKeysRequest
{
    public int Version { get; set; }
    public Content Content { get; set; }
    public Protection Protection { get; set; }
    public KeyTiming KeyTiming { get; set; }
}
public class Content
{
    public string Id { get; set; }
    public string Type { get; set; }
}

public class Protection
{
    public ProtecionSystem ProtectionSystem{ get; set; }
}

public class ProtecionSystem
{
    public string Type { get; set; }
    public string SystemId { get; set; }
}

public class KeyTiming
{
    public int Position { get; set; }
}

当我收到没有标头的请求时

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

映射工作得很好,但是当我添加标题时,它会中断。 我怎样才能忽略它?

    [HttpPost]
    [Route("{instanceId}")]
    public object AcquireKeyRequest([FromUri]int instanceId, AcquireKeysRequest xml)
    {
       //SomeLogicHere
    }

P.S:我知道模型和 XML 中的名称是不同的,我已经在我的代码中修复了。

【问题讨论】:

    标签: c# xml asp.net-web-api xml-serialization


    【解决方案1】:

    在您的 MVC Web API 项目中,请通过 NuGet 添加以下包: Microsoft.AspNetCore.Mvc.Formatters.Xml

    然后在您的 startup.cs 中。调整以下内容以普遍启用 XML 序列化和反序列化。

     public void ConfigureServices(IServiceCollection services)
     {
        services.AddMvc(options =>
        {
           options.Filters.Add(new ProducesAttribute("application/xml"));
        }).AddXmlSerializerFormatters();
     }
    

    最后用控制器创建一个 Get 和 Post 方法并尝试一下。对我来说,这两种情况都有效。带或不带 xml-tag。

     [HttpGet]
     public AcquireKeysRequest Get()
     {
         AcquireKeysRequest req = new AcquireKeysRequest();
         req.KeyTiming = new KeyTiming() { Position = 2 };
         req.Protection = new Protection()
         {
             ProtectionSystem = new ProtecionSystem() {
                  SystemId = "wkow", Type = "type"
             }
         };
         req.Version = 2;
         req.Content = new Content() { Id = "id", Type = "type" };
         return req;
     }
    
     [HttpPost]
     public void Post([FromBody]AcquireKeysRequest value)
     {
     }
    

    我希望我能帮忙。

    干杯

    【讨论】:

    • 嗨@哈杜。我的 WebApi 不是 .NetCore,是 .NetFramework 4.6.2 我还没有尝试过,但我猜这应该只适用于 .NetCore,我错了吗?
    • 我认为在这种特殊情况下没有什么不同。但是试试看.. sry.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-18
    • 1970-01-01
    • 1970-01-01
    • 2020-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多