C#如何忽略对WebApi的请求中的Xml标头?

时间:2018-10-10 19:33:23

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

我正在创建到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中的名称是不同的,我已经在代码中固定了。

1 个答案:

答案 0 :(得分:0)

在您的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 and Post方法,然后尝试一下。对我来说,这两种情况都有效。带有或不带有xml标签。

 [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)
 {
 }

我希望我能帮上忙。

欢呼