wCF服务返回xml而不是预期的json

时间:2014-01-17 15:56:24

标签: asp.net json wcf extjs

我试图进行webservice调用以返回json格式的数据以填充网格控件。它没有工作,在使用fiddler和firebug监视调用后,我看到数据包装为xml。我尝试了不同的电话;一个人调用mongodb,结果是一个简单的集合,另一个是来自另一个json格式的端点的数据。我的网络服务设置如下:

Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel
Imports System.Web.Script.Services
Imports System.Web.Script.Serialization
Imports System.Net
Imports System.IO
Imports System.Xml
Imports Newtonsoft.Json
Imports System.ServiceModel
Imports MongoDB.Driver
Imports MongoDB.Bson


  <System.Web.Script.Services.ScriptService()> _
  <System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
  <ServiceBehaviorAttribute(IncludeExceptionDetailInFaults:=True)>
  <ToolboxItem(False)> _
  Public Class WebService1
   Inherits System.Web.Services.WebService

     Private mongo As MongoServer = MongoServer.Create()
    Private Function convertToJson(ByVal username As String)

    Dim product As New splnkObject()
    product.userName = username

    Dim jsonT As String = JsonConvert.SerializeObject(product)

    Return jsonT

   End Function

   <WebMethod()> _
  <ScriptMethod(UseHttpGet:=True, 
   XmlSerializeString:=False,     ResponseFormat:=ResponseFormat.Json)> _
   Public Function getDBData() As String

    Dim response As String = String.Empty

    mongo.Connect()
    Dim db = mongo.GetDatabase("nodetest1")

    Using mongo.RequestStart(db)
        Dim collection = db.GetCollection(Of BsonDocument)("usercollection").FindAll()

        response = collection.Collection.ToString
        response = "{""d"":" + response + "}"

        Return collection.ToArray.ToJson

    End Using
  End Function

这是在fiddler中捕获的响应,json选项卡在正文中表示无效的json:

 string [ xmlns=http://tempuri.org/ ]
 [{ "_id" : ObjectId("52d2f2b3c60804b25bc5d2ca"), "username" : "testuser1", 
  "email" :   "testuser1@testdomain.com" }, 
 { "_id" : ObjectId("52d2f2f9c60804b25bc5d2cb"),    "username" : "testuser2", 
  "email" :    "testuser2@testdomain.com" },    
 { "_id" : ObjectId("52d2f2f9c60804b25bc5d2cc"), "username" : "testuser3", 
 "email" : "testuser3@testdomain.com" }]

我的webconfig文件如下:

<?xml version="1.0"?>
<configuration>
  <appSettings>
  <add key="connectionString2" value="Server=localhost:27017"/>
 </appSettings>
<connectionStrings>
 <system.web>
<authentication mode="None" />
  <authorization>
    <allow users="?" />
  </authorization>
 <compilation debug="true" strict="false" explicit="true" targetFramework="4.0">
  <assemblies>
    <add assembly="System.Data.Linq, Version=4.0.0.0, 
      Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
   </assemblies>
</compilation>
<httpHandlers>
  <remove verb="*" path="*.asmx"/>
  <add verb="*" path="*.asmx" 
       type="System.Web.Script.Services.ScriptHandlerFactory" validate="false"/>
  </httpHandlers>
  <webServices>
    <protocols>
    <add name="HttpGet"/>
    <add name="HttpPost"/>
  </protocols>
 </webServices>
</system.web>
 <system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="false"
  multipleSiteBindingsEnabled="true" />
<services>
  <service name="WbTest.Service1">
    <endpoint address="" behaviorConfiguration="WbTest.Service1AspNetAjaxBehavior"
      binding="webHttpBinding" contract="WbTest.IService1" />
  </service>
  </services>
  <behaviors>
    <endpointBehaviors>
      <behavior name="WebBehavior">
      <webHttp />
      <enableWebScript />
      </behavior>
      <behavior name="WbTest.Service1AspNetAjaxBehavior">
      <enableWebScript />
      </behavior>
    </endpointBehaviors>
    <serviceBehaviors>
    <behavior name="">

      <serviceDebug includeExceptionDetailInFaults="false" />
    </behavior>
  </serviceBehaviors>
   </behaviors>
   <bindings />
    <client />
   </system.serviceModel>
   </configuration>

javascript调用:

  var myStore = new Ext.data.Store({
    model: 'User',
    proxy: {
        type: 'ajax',
        url: 'WCFService/WebService1.asmx/getDBData',
        contentType: 'application/json; charset=utf-8',
        reader: {
            type: 'json',
            root: '_id'
        }
    }
  });
   myStore.load();

请有人看看并确定问题所在。

1 个答案:

答案 0 :(得分:2)

我不会说这是“正确的”方式,但是,一种选择是指定方法的返回类型并直接写 到响应(HttpContext.Current.Response)对象。

   <WebMethod()> _
   Public Sub getDBData()
    Dim response As String = String.Empty

    mongo.Connect()
    Dim db = mongo.GetDatabase("nodetest1")

    Using mongo.RequestStart(db)
        Dim collection = db.GetCollection(Of BsonDocument)("usercollection").FindAll()

        response = collection.Collection.ToString
        response = "{""d"":" + response + "}"
        Dim responseJson as String
        responseJson = Collection.ToArray.ToJson
        HttpContext.Current.Response.Write(responseJson)
    End Using
  End Sub

此外,如果您打算使用Newtonsoft来操作对象,我发现此方法效果很好。

我应该注意,asmx web services是遗产,新技术是wcf