遇到无效的根元素名称'HTML'。 'root'是唯一允许的根元素名称

时间:2011-03-07 18:20:24

标签: c# wcf

我正在使用msdn示例代码,它有jsonp包装文件,你可以在这里找到代码

这个article和MSDN文章JSON with Padding(AJAX)

但是当我运行代码时,它会抛出这个错误:

Encountered invalid root element name 'HTML'. 'root' is the only allowed root element name

这是什么意思?

enter image description here

3 个答案:

答案 0 :(得分:5)

这意味着您已经制作了某种类型的Web请求,希望能够获得某种XML数据,而不是获取HTML数据。通常的原因是混乱的URL。如果您的URL正确,则将按预期返回XML。由于它搞砸了你最终得到回来的HTML(可能是一个错误页面)。

检查您的网址以确保其正确无误。

答案 1 :(得分:2)

我找到了类似问题的解决方案。在我的情况下,当我的服务返回原始JSON时,我得到了类似的错误,也就是说它返回了代表这个JSON的Stream。

错误是:遇到无效的根元素名称'Binary'。 'root'是唯一允许的根元素名称。

问题是MS提供的示例使用JsonWriter将消息转换为JSON,但是此编写者希望您的消息包含可以转换为Stream的JSON对象。在我的情况下,消息是由二进制数据组成的,所以我没有一个“根”元素而是“Binary”元素。

我通过修改MS样本提供的类来解决这个问题。基本上我检查消息的格式 - 如果它是JSON我仍然可以使用JsonWriter,如果是二进制,我必须采取不同的方法。在你的情况下,消息是HTML格式(我不知道你如何提供它),但你会找到一种不同的方式来获取消息的正文。

我在这里写了一篇关于我的问题的博文:http://hoonzis.blogspot.com/2011/07/provide-jsonp-with-your-wcf-services.html

希望它有所帮助,Honza

答案 2 :(得分:0)

我遇到了相同的错误消息,但是在不同的场景中。我正在向仅支持XML的WCF Web服务添加JSON支持。

具体来说,我也希望在JSON中返回错误消息对象。 我有一个正在实施System.ServiceModel.Dispatcher.IErrorHandler的课程。在ProvideFault方法中,我将`WebBodyFormateMessageProperty设置为相应的一个wither,XML或JSON,基于它在accept头中传递的内容。我还相应地设置了内容类型。我缺少的是为每个案例使用正确的序列化器

    Dim webBodyFormatMessageProp As Channels.WebBodyFormatMessageProperty
    Dim contentType As String
    Dim serializer As XmlObjectSerializer
    If WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Json Then
        webBodyFormatMessageProp = New System.ServiceModel.Channels.WebBodyFormatMessageProperty(System.ServiceModel.Channels.WebContentFormat.Json)
        contentType = "application/json"
        serializer = New DataContractJsonSerializer(GetType(MyErroClass))
    Else
        webBodyFormatMessageProp = New System.ServiceModel.Channels.WebBodyFormatMessageProperty(System.ServiceModel.Channels.WebContentFormat.Xml)
        contentType = "text/xml"
        serializer = New DataContractSerializer(GetType(MyErroClass))
    End If

    Dim detail = faultException.[GetType]().GetProperty("Detail").GetGetMethod().Invoke(faultException, Nothing)
    fault = System.ServiceModel.Channels.Message.CreateMessage(version, "", detail, serializer)
    fault.Properties.Add(System.ServiceModel.Channels.WebBodyFormatMessageProperty.Name, webBodyFormatMessageProp)

    Dim httpResponseMessageProp = New System.ServiceModel.Channels.HttpResponseMessageProperty()
    httpResponseMessageProp.Headers(System.Net.HttpResponseHeader.ContentType) = contentType
    httpResponseMessageProp.StatusCode = System.Net.HttpStatusCode.OK
    httpResponseMessageProp.StatusDescription = [error].Message

    fault.Properties.Add(System.ServiceModel.Channels.HttpResponseMessageProperty.Name, httpResponseMessageProp)

为VB.net道歉,但这正是我目前正在进行的工作。