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

在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) {
        //context.Response.ContentType = "text/plain";
        context.Response.Write("Hello World");
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}


评论: 0 | 引用: 0 | 查看次数: 6221
发表评论
登录后再发表评论!