2012-02-27 114 views
2

我想創建一個簡單的AJAX & Web服務測試(使用C#.Net 2.0)以JSON格式返回數據,並且我(我相信)我需要的一切,但我一遍又一遍地遇到同樣的問題。來自Web服務的響應始終是XML。 (它總是有<?xml version="1.0" encoding="utf-8"?>作爲第一行)。ASP.Net Web服務不會返回JSON - 總是XML

我試過ScriptMethod標籤內的各種選項,但沒有什麼區別。

該調用工作正常,但我得到一個「parsererror」與響應,我期望,因爲它不是有效的JSON。我可以在瀏覽器中調用Web服務方法,並以XML格式獲得我期望的返回值。提琴手還表明,請求和響應是我發現的。

在這裏已經有幾個關於完全相同的問題的問題,但他們都沒有給我一個工作答案。

如果您需要更多信息,請提問。

C#

using System; 
using System.Collections.Generic; 
using System.Web; 
using System.Web.Services; 
using System.Web.Script.Services; 
using System.Web.Script.Serialization; 

namespace jQueryWebServiceTest 
{ 
    /// <summary> 
    /// This is a simple web service to test calling from javascript using AJAX, and getting a response. 
    /// </summary> 
    [WebService(Namespace = "http://tempuri.org/")] 
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
    [System.ComponentModel.ToolboxItem(false)] 
    [ScriptService] 
    public class Service1 : System.Web.Services.WebService 
    { 
     [WebMethod] 
     [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
     public string SayHello() 
     { 
      // I've tried both this... 
      var response = new { value = "Hello" }; 
      JavaScriptSerializer json = new JavaScriptSerializer(); 
      return json.Serialize(response); 

      // and this... 
      return "Hello"; 
     } 
    } 
} 

的Javascript

$(function() { 

    var data = JSON.stringify({ Name: "John" }); // This is not used - part of other testing. 
    data = "{}"; 

    $.ajax({ 
     type: "POST", 
     data: data, 
     url: "TestService.asmx/SayHello", 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     success: function (data) { 
      console.log(data); 
     }, 
     error: function (error, status) { 
      console.log("status = " + status); 
      console.log(error); 
     } 
    }); 

}); 
+0

看看這個答案:http://stackoverflow.com/a/663860/701062 – 2012-02-27 17:18:11

+0

感謝加里。我已經看到了一個,但它不相關,因爲我使用.Net 2.0(我將修改問題以反映這一點)。非常感謝。 – Archer 2012-02-27 17:20:04

+0

@Archer其實你不得不使用.Net 3.5。直到該版本才引入ScriptMethod屬性。 – JamieSee 2012-02-27 17:31:02

回答

2

我設法得到它通過將以下2個街區到web.config工作...

configuration塊內system.web ...

<assemblies> 
    <add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> 
</assemblies> 

和其他地方,裏面system.web ...

<httpHandlers> 
    <remove verb="*" path="*.asmx"/> 
    <add verb="*" path="*.asmx" type="System.Web.Script.Services.ScriptHandlerFactory" validate="false"/> 
</httpHandlers>