简体   繁体   English

Restsharp-尝试在根节点上序列化xmlns属性时出错

[英]Restsharp - Error attempting to serialize xmlns attribute on root node

When attempting to serialize an object to XML using RestSharp that contains an xmlns attribute on the root node, I receive the following exception: 当尝试使用在根节点上包含xmlns属性的RestSharp将对象序列化为XML时,我收到以下异常:

The prefix '' cannot be redefined from '' to ' https://someurl.com ' within the same start element tag. 不能在同一开始元素标记中将前缀“”从“”重新定义为“ https://someurl.com ”。

The object I'm attempting to serialize only contains one property (for now), the XmlNamespace: 我尝试序列化的对象仅包含一个属性(目前),即XmlNamespace:

[SerializeAs(Name = "root")]
public class Root
{
    [SerializeAs(Name = "xmlns", Attribute = true)] 
    public String XmlNamespace { get; set; }
}

The exception occurs when trying to add my object to the request body, like so: 尝试将我的对象添加到请求主体时会发生异常,如下所示:

Root requestBody = new Root();

requestBody.XmlNamespace = "https://someurl.com";

var request = new RestRequest();

request.Method = Method.POST;
request.Resource = "orders";
request.RequestFormat = DataFormat.Xml;

request.AddBody(requestBody); // exception occurs here

I've tried using the XmlNamespace property of the RestRequest as well as instantiating a new XmlSerializer for the RestRequest, but neither of these have appended the namespace to the root node as required by the API I'm attempting to access. 我尝试使用RestRequest的XmlNamespace属性以及为RestRequest实例化一个新的XmlSerializer,但是这些都没有按照我尝试访问的API的要求将名称空间附加到根节点。 Does anybody happen to know how to properly serialize an xmlns attribute in RestSharp? 有人碰巧知道如何在RestSharp中正确序列化xmlns属性吗?

I wound up finding the answer. 我终于找到答案了。 It looks like I was thrown off by the presence of XmlNamespace properties at the request and XmlSerializer levels. 看起来我被请求级别和XmlSerializer级别的XmlNamespace属性的存在吓到了。 For anybody else that runs into this issue, the fix was to define the namespace when calling the AddBody method as follows: 对于遇到此问题的其他任何人,解决方法是在调用AddBody方法时定义命名空间,如下所示:

request.AddBody(requestBody, "https://someurl.com"); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM