木子屋 Dnawo's BLOG

VS2005一般处理程序(.ashx)示例

👤 dnawo 📅 2009-05-24 👁 6710 👍 0 💬 0 🔄 来源:本站原创
在Web应用程序中,有时需要做个接口,该接口能接收以http get或post方式传递过来的数据,进行适当处理后在页面中输出结果返回给其他应用程序,显然,在页面中不能有html代码,所以我们得手工将全部html代码删除:

Query.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Query.aspx.cs" Inherits="Query" %>

Query.aspx.cs:
public partial class Query : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        int key = 0;

        if (HttpContext.Current.Request["key"] != null)
        {
            key = Convert.ToInt16(HttpContext.Current.Request["key"]);

            if (key > 9 && key < 21)
            {
                HttpContext.Current.Response.Write("1_http://www.mzwu.com/");
                return;
            }
        }

        HttpContext.Current.Response.Write("0_Error");

    }
}

使用一般处理程序(.ashx),我们就可以不必理会html相关内容,将精力放在代码上:

Query.ashx:
<%@ WebHandler Language="C#" Class="Query" %>

using System;
using System.Web;

public class Query : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        int key = 0;

        if (context.Request["key"] != null)
        {
            key = Convert.ToInt16(context.Request["key"]);

            if (key > 9 && key < 21)
            {
                context.Response.Write("1_http://www.mzwu.com/");
                return;
            }
        }

        context.Response.Write("0_Error");
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}


----------------------------------------------------------------------

说明:运行一般处理程序默认的代码会提示:文档的顶层无效。按下边修改即可:
<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;

public class Handler : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        [color=Green]//context.Response.ContentType = "text/plain";[/color]
        context.Response.Write("Hello World");
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

评论(0)

暂无评论。

验证码
评论需审核通过后显示
← 上一篇 升级Windows服务引用的程序集(dll)测试 下一篇 → 周鸿祎:我赌1万块 马云跟雅虎合作一定痛苦