我正在使用MSDN示例代码,它有jsonp包装文件,你可以在这里找到代码。
这是文章和MSDN文章JSON with Padding (AJAX)
但当我运行代码时,它抛出了这个错误:
遇到无效的根元素名称“HTML”。只允许“root”作为根元素名称
这是什么意思?
我在不同的情况下遇到了相同的错误信息。我正在为一个只支持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,我很抱歉,但那是我目前正在工作的语言。