使用ASP.NET一般处理程序或WebService返回JSON的实现代码

所属分类: 网络编程 / ASP.NET 阅读数: 300
收藏 0 赞 0 分享

示例代码下载: http://zsharedcode.googlecode.com/files/JQueryElementDemo.rar

本文中所包含的内容如下:

  * 准备
  * 一般处理程序/ashx
  * WebService/asmx准备

如果希望通过 ashx 或者 asmx 来返回 JSON, 那么需要引用程序集 System.Web.Extensions.dll, 在 .NET 3.5, 4.0 中已经默认包含. 对于 .NET 2.0, 3.0, 需要安装 ASP.NET 2.0 AJAX, 可以在 http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=883 下载.

一般处理程序/ashx

使用一般处理程序返回 JSON, 对于不同版本的 .NET 都是类似, 请看下面的 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 或者是源代码.

实际过程演示: http://www.tudou.com/programs/view/rHCYHX9cmcI/, 建议全屏观看.

欢迎访问 panzer 开源项目, http://zsharedcode.googlecode.com/ , 其中包含了 IEBrowser 控制 WebBrowser 执行各种 js 和 jQuery 脚本以及录制功能 和 jQueryUI 的 Asp.net 控件 JQueryElement.
更多精彩内容其他人还在看

解析WPF实现音频文件循环顺序播放的解决方法

本篇文章是对WPF实现音频文件循环顺序播放的方法进行了详细的分析介绍,需要的朋友参考下
收藏 0 赞 0 分享

解决.net framework 4.0环境下遇到版本不同编译不通过的方法详解

本篇文章是对.net framework 4.0环境下遇到版本不同编译不通过的解决方法进行了详细的分析介绍,需要的朋友参考下
收藏 0 赞 0 分享

将文件上传、下载(以二进制流保存到数据库)实现代码

将文件以二进制流的格式写入数据库:首先获得文件路径,然后将文件以二进制读出保存在一个二进制数组中具体请祥看本文,希望对你有所帮助
收藏 0 赞 0 分享

点击提交按钮后DropDownList的值变为默认值实现分析

在点击提交按钮后,页面上所有的绑定到数据库的控件值都恢复到默认值,下面与大家分享下DropDownList的值变为默认值
收藏 0 赞 0 分享

ASP.NET web.config中数据库连接字符串connectionStrings节的配置方法

ASP.NET web.config中数据库连接字符串connectionStrings节的配置方法,需要的朋友可以参考一下
收藏 0 赞 0 分享

Linkbutton控件在项目中的简单应用

Button控件可分为button控件、LinkButton控件、ImageButton控件三类,而LinkButton控件则在页面上显示为一个超级链接,下面与大家分享下其具体应用
收藏 0 赞 0 分享

Web.config 和 App.config 的区别分析

Web.config 和 App.config 的区别分析,需要的朋友可以参考一下
收藏 0 赞 0 分享

基于.Net中的数字与日期格式化规则助记词的使用详解

本篇文章是对.Net中的数字与日期格式化规则助记词的使用进行了详细的分析介绍,需要的朋友参考下
收藏 0 赞 0 分享

解决在Web.config或App.config中添加自定义配置的方法详解

本篇文章是对在Web.config或App.config中添加自定义配置的方法进行了详细的分析介绍,需要的朋友参考下
收藏 0 赞 0 分享

深入本机影像生成器(Ngen.exe)工具使用方法详解

本篇文章是对本机影像生成器(Ngen.exe)工具使用方法进行了详细的分析介绍,需要的朋友参考下
收藏 0 赞 0 分享
查看更多