【问题标题】:wCFService returning xml instead of expected jsonwCFService 返回 xml 而不是预期的 json
【发布时间】:2014-01-17 15:56:23
【问题描述】:

我试图进行 Web 服务调用以返回 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 选项卡显示 body 中的 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();

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

【问题讨论】:

    标签: asp.net json wcf extjs


    【解决方案1】:

    我不会说这是“正确”的方式,但是,一种选择是在方法上指定返回类型并直接编写到响应(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

    【讨论】:

      猜你喜欢
      • 2014-07-11
      • 2016-07-16
      • 2012-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-24
      相关资源
      最近更新 更多