ASP.NET MVC Web Api: application/xml PUT 请求 body 在服务器端为空

ASP.NET MVC Web Api: application/xml PUT request body is null on server side

我正在尝试手动将一些 XML 内容发送到我创建的 ASP MVC Web Api 服务器。 Controller.Put() 方法如下所示:

public Game Put(int id, [FromBody] HttpAction[] actions)
{
     Debug.WriteLine(actions[0].TargetId + ", " + actions[0].Type + ", " +   actions[0].ContentType + ", " + actions[0].Contents);
     Game game = this.provider.Update(id, actions);
     return game; 
}

在检查操作 object 的参数时立即出现空引用。 此方法接收一个 object Id 和一个 HttpAction 类型的数组,如下所示:

[DataContract]
public class HttpAction
{
    [DataMember]
    public int TargetId { get; set; }
    [DataMember]
    public HttpActionType Type { get; set; }
    [DataMember]
    public HttpActionContentType ContentType { get; set; }
    [DataMember]
    public string Contents { get; set; }
}

我已经像这样设置了我的 PUT 请求:

Header

(以上大部分是由我用来发送请求的 Advanced Rest Client 生成的)

Body

<?xml version="1.0" encoding="utf-8"?>
<HttpActions>
   <HttpAction>
     <TargetId>0</TargetId>
     <Type>Add</Type>
     <ContentType>Player</ContentType>
     <Contents>UnityPlayer</Contents>
   </HttpAction>
</HttpActions>

body的另一次尝试:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfHttpAction xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<HttpAction>
  <TargetId xmlns="http://schemas.datacontract.org/2004/07/GOHCGLibrary.Actions">0</TargetId>
  <Type xmlns="http://schemas.datacontract.org/2004/07/GOHCGLibrary.Actions">Add</Type>
  <ContentType xmlns="http://schemas.datacontract.org/2004/07/GOHCGLibrary.Actions">Player</ContentType>
  <Contents xmlns="http://schemas.datacontract.org/2004/07/GOHCGLibrary.Actions">UnityPlayer</Contents>
</HttpAction>
</ArrayOfHttpAction>

每当我发送这个请求时,我发现控制器中请求的 body 为空。我在使用 JSON body 时设法对其进行了测试并且它工作正常,我还在我的控制器上进行了单元测试,该单元测试传入 HttpAction 数组以检查所有后台代码是否正常工作。

在为请求构建 XML 时,我做错了什么?我读过我需要包括 xmlns 和 xmlns:i 但我不确定它们的用途或设置它们的目的。我尝试了各种选择但没有成功。

把你的方法改成这个

public Game Put(HttpAction[] actions)
{
}

对于单品,你应该试试这个 request body

<HttpAction xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/WebApiSample.Models">
  <ContentType>sample string 3</ContentType>
  <Contents>sample string 4</Contents>
  <TargetId>1</TargetId>
  <Type>sample string 2</Type>
</HttpAction>

试试这个内容类型

Content-Type: application/xml

对于 HttpAction 列表,您应该尝试以下类型的 request body

<ArrayOfHttpAction xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/WebApiSample.Models">
 <HttpAction>
    <ContentType>sample string 3</ContentType>
    <Contents>sample string 4</Contents>
    <TargetId>1</TargetId>
    <Type>sample string 2</Type>
 </HttpAction>
 <HttpAction>
    <ContentType>sample string 3</ContentType>
    <Contents>sample string 4</Contents>
    <TargetId>1</TargetId>
    <Type>sample string 2</Type>
 </HttpAction>
</ArrayOfHttpAction>

Note: Don't use <?xml version="1.0" encoding="utf-8"?> in you request body