Restsharp – 由于XElement属性导致的异常

我需要发出一个REST请求并传递一个具有XElement类型属性的对象.

物体:

public class Test
{
    public string Property1 {get;set;}
    public XElement PropertyXml {get;set;}
}

代码:

var testObj = new Test();
testObj.Property1 = "value";
testObj.PropertyXml = new XElement("test");
var level1 = new XElement("level1", "value111");
testObj.PropertyXml.Add(level1);

var client = new RestClient();

client.BaseUrl = new Uri(string.Format(_url));
var rRequest = new RestRequest(_address, Method.POST);
rRequest.RequestFormat = DataFormat.Json;
rRequest.AddBody(testObj);
var response = client.Execute(rRequest);

我在AddBody调用的行中得到’System.StackOverflowException’.
PS我可以使用HttpClient(我使用PostAsJsonAsync方法)而不是Restsharp传递Test对象.

任何想法,将不胜感激 ..

最佳答案 RestSharp没有XElement的固有知识,并且AddBody将尝试通过遍历其属性来序列化它,就像任何其他POCO类型一样.你可以很容易地看到这个过程陷入无限循环:

testObj.FirstNode.Parent.FirstNode.Parent....

最好的办法是将PropertyXml属性的类型更改为XML结构可以轻松映射到的简单POCO类型.就像是:

public class PropertyStructure
{
    public string level1 {get;set;}
}

public class Test
{
    public string Property1 {get; set;}
    public PropertyStructure PropertyXml {get; set;}
}
点赞