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

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

这是文章和MSDN文章JSON with Padding (AJAX)

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

遇到无效的根元素名称“HTML”。只允许“root”作为根元素名称

这是什么意思?

enter image description here

3个回答

6
这意味着您发出了某种网络请求,期望得到一些XML数据返回,但实际上得到的是HTML数据。通常的原因是URL出现问题。如果您的URL正确,那么预期会返回XML。由于URL出现问题,您最终得到了HTML(可能是错误页面)。请检查您的URL以确保它们是正确的。

2
我找到了类似问题的解决方案。在我的情况下,当我的服务返回原始JSON时,也就是说它返回了代表此JSON的流时,我会遇到类似的错误。
错误为:遇到无效的根元素名“Binary”。只允许使用“root”作为根元素名。
问题是MS提供的示例使用JsonWriter将消息转换为JSON,但这个写入器期望你的消息由他可以转换为流的JSON对象组成。在我的情况下,消息由二进制数据组成,因此我有“Binary”元素而不是一个“root”元素。
我通过修改MS示例提供的类来解决这个问题。基本上,我检查消息的格式-如果它是JSON,我仍然可以使用JsonWriter,如果它是二进制的,则必须采用不同的方法。在您的情况下,消息以HTML格式呈现(我不确定您如何提供它),但是您会找到获取消息正文的不同方式。
我在这里写了一篇关于我的问题的博客文章:http://hoonzis.blogspot.com/2011/07/provide-jsonp-with-your-wcf-services.html 希望它能有所帮助,Honza

0

我在不同的情况下遇到了相同的错误信息。我正在为一个只支持XML的WCF Web服务添加JSON支持。

具体来说,我想要在JSON中返回错误消息对象。 我有一个实现了System.ServiceModel.Dispatcher.IErrorHandler的类。在ProvideFault方法中,我设置了`WebBodyFormateMessageProperty`与接受头中传递的内容类型(XML或JSON)相对应。我还相应地设置了内容类型。我错过的是每种情况下使用正确的序列化程序。

    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,我很抱歉,但那是我目前正在工作的语言。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接