我正在尝试手动将一些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;
}
检查操作对象上的参数时,会立即发生空引用。 此方法接收对象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请求:
标题
(以上大部分是由我用来发送请求的Advanced Rest Client生成的)
车身
<?xml version="1.0" encoding="utf-8"?>
<HttpActions>
<HttpAction>
<TargetId>0</TargetId>
<Type>Add</Type>
<ContentType>Player</ContentType>
<Contents>UnityPlayer</Contents>
</HttpAction>
</HttpActions>
身体的另一次尝试:
<?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>
每当我发送此请求时,我发现控制器中请求的主体为空。我已经设法在使用JSON主体时测试它并且它工作正常,我也在我的控制器上进行单元测试,传递HttpAction数组以检查所有后台代码是否正常工作。
在为请求构建XML时,我做错了什么?我已经读过我需要包含xmlns和xmlns:i但是我不确定这些是什么或者设置它们是什么。我尝试过各种各样的选择却没有成功。
答案 0 :(得分:1)
将方法改为此
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>
注意:请勿在您的请求中使用
<?xml version="1.0" encoding="utf-8"?>
体