asp.net WebService 返回 JSON操作方法

來源:互聯網
上載者:User

請看下面的 handler.ashx 的代碼:

 代碼如下 複製代碼

<%@ WebHandler Language="C#" Class="handler" %>

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

public class handler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/javascript";
        context.Response.Cache.SetNoStore ( );

        string name = context.Request["name"];

        SortedDictionary<string, object> values = new SortedDictionary<string, object>();
        values.Add("message",
            string.IsNullOrEmpty(name) ? "無名氏" :
            string.Format("你好 {0}, {1}", name, DateTime.Now));

        context.Response.Write(new JavaScriptSerializer().Serialize(values));
    }

    public bool IsReusable
    {
        get { return false; }
    }

}

上面的例子中, 通過 JavaScriptSerializer 類的 Serialize 方法, 將對象轉化為 JSON 對應的字串. 而轉化的對象是 SortedDictionary, 會產生 { "message": "你好 x, 20xx-xx-xx xx:xx:xx" } 這樣類似的字串. 如果需要返回數組, 可以定義 object[] 來轉換. 代碼中還使用了 context.Response.Cache.SetNoStore ( ); 來讓瀏覽器每次請求 ashx 時都重新訪問, 而不是使用緩衝.

如果使用 jQuery, 可以使用下面的函數來接收 JSON:

 代碼如下 複製代碼

function(data){
    alert(data.message);
}

WebService/asmx

在不同版本的 .NET 中, 通過 javascript 訪問 WebService 並返回 JSON 是略有不同的. 首先, 可以分別採用不同的 Web.config 檔案.法全部列出, 如有需要請參考:

.NET 2.0, 3.0 Web.config

 代碼如下 複製代碼

<?xml version="1.0"?>
<configuration>
    <system.web>
        <compilation debug="true">
            <assemblies>
                <add
assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            </assemblies>
        </compilation>
        <pages/>
        <httpHandlers>
            <remove verb="*" path="*.asmx"/>
            <add verb="*" path="*.asmx"
                type="System.Web.Script.Services.ScriptHandlerFactory"
                 validate="false"/>
        </httpHandlers>
    </system.web>
</configuration>

.NET 3.5 Web.config

.NET 4.0 Web.config

以上兩個版本的 Web.config 可以在樣本壓縮包中的 Web.3.5.config 和 Web.4.config 中查看.

下面是 webservice.asmx/webservice.cs 的代碼:

 代碼如下 複製代碼

<%@ WebService Language="C#" CodeBehind="~/App_Code/webservice.cs" Class="webservice" %>
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
using System.Collections.Generic;

[WebService ( Namespace = "http://tempuri.org/" )]
[WebServiceBinding ( ConformsTo = WsiProfiles.BasicProfile1_1 )]
[ScriptService]
public class webservice : System.Web.Services.WebService
{

    [WebMethod]
    [ScriptMethod]
    public SortedDictionary<string, object> Save ( string name )
    {
        this.Context.Response.Cache.SetNoStore ( );

        SortedDictionary<string, object> values = new SortedDictionary<string, object> ( );
        values.Add ( "message",
            string.IsNullOrEmpty ( name ) ? "無名氏" :
            string.Format ( "你好 {0}, {1}", name, DateTime.Now ) );

        return values;
    }

}

 

為類添加屬性 ScriptService, 並對類中的方法使用屬性 ScriptMethod, 可以讓 javascript 來調用這些方法. 這裡不需要再使用 JavaScriptSerializer 將對象轉化為 JSON 字串, 而是直接返回對象即可. 上面的代碼中返回了 SortedDictionary, 在 .NET 2.0, 3.0 中將類似於 { "message": "你好 x, 20xx-xx-xx xx:xx:xx" } 的形式, 而對於 .NET 3.5, 4.0 則是 { "d": { "message": "你好 x, 20xx-xx-xx xx:xx:xx" } }, 因此可以分別在 jQuery 中使用下面的函數來接受 JSON:

 代碼如下 複製代碼

function(data){
    alert(data.message);
}

function(data){
    alert(data.d.message);
}

JQueryElement 是開源共用程式碼, 可以在 http://code.google.com/p/zsharedcode/wiki/Download 頁面下載 dll 或者是原始碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.