.ashx 文件

 
原文链接:https://www.cnblogs.com/ranran/p/3850870.html
一般处理程序(HttpHandler)是·NET众多web组件的一种,ashx是其扩展名。
一个httpHandler接受并处理一个http请求,类比于Java中的servlet。类比于在Java中需要继承HttpServlet类。在net中需要实现IHttpHandler接口,这个接口有一个IsReusable成员,一个待实现的方法ProcessRequest(HttpContextctx) 。程序在processRequest方法中处理接受到的Http请求。成员IsReusable指定此IhttpHandler的实例是否可以被用来处理多个请求。
.ashx程序适合产生供浏览器处理的、不需要回发处理的数据格式,例如用于生成动态图片、动态文本等内容

(1)、使用举例
.ashx文件是主要用来写web handler的。使用.ashx 可以让你专注于编程而不用管相关的web技术。我们熟知的.aspx是要做html控件树解析的,.aspx包含的所有html实际上是一个类,所有的html都是类里面的成员,这个过程在.ashx是不需要的。ashx必须包含IsReusable属性(这个属性代表是否可复用,通常为true),而如果要在ashx文件用使用Session必须实现IRequiresSessionState接口.
一个简单的实现修改登录用户密码的示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />-->using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.SessionState;
 
namespace Test
{
 
    public class HandlerTest : IHttpHandler, IRequiresSessionState
    {
 
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ClearContent();
            context.Response.ContentType = "text/plain";
            context.Response.Cache.SetCacheability(HttpCacheability.NoCache); //无缓存
 
            string action = context.Request.Params["action"]; //外部请求
            if (action == "modifyPwd"//用户改密码
            {
                string oldPwd = context.Request.Params["pwd"];
 
                //在ashx文件用使用Session必须实现IRequiresSessionState接口
                //Session["LogedUser"]是登录用户的会话,用户名和密码都是test
                if (oldPwd.ToUpper() != ((context.Session["LogedUser"]) as Customer).Password.ToUpper()) //用户输入的旧密码和当前登录用户的不相同
                {
                    context.Response.Write("旧密码输入错误!");
                }
                else
                {
                    context.Response.Write("旧密码输入正确!");
                }
            }
 
 
            context.Response.End();
        }
 
        public bool IsReusable
        {
            get
            {
                return true;
            }
        }
    }
}

  客户端的调用(js和页面部分):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />--><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ASHXTest.aspx.cs" Inherits="ASHXTest" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>mytest</title>
    <script type="text/javascript">
        function $(s) { if (document.getElementById) { return eval('document.getElementById("' + s + '")'); } else { return eval('document.all.' + s); } }
 
        function createXMLHTTP() {
            var xmlHttp = false;
            var arrSignatures = ["MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0",
                         "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP",
                         "Microsoft.XMLHTTP"];
            for (var i = 0; i < arrSignatures.length; i++) {
                try {
                    xmlHttp = new ActiveXObject(arrSignatures[i]);
                    return xmlHttp;
                }
                catch (oError) {
                    xmlHttp = false; //ignore
                }
            }
            // throw new Error("MSXML is not installed on your system."); 
            if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
                xmlHttp = new XMLHttpRequest();
            }
            return xmlHttp;
        }
 
        var xmlReq = createXMLHTTP();
 
        // 发送ajax处理请求(这里简单验证旧密码的有效性)
        function validateOldPwd(oTxt) {
            var url = "/HandlerTest.ashx?action=modifyPwd&pwd=" + escape(oTxt.value); //.ashx文件
            xmlReq.open("get", url, true);
            xmlReq.setRequestHeader("If-Modified-Since", "0");
            xmlReq.onreadystatechange = callBack;
            xmlReq.send(url); // 发送文本
        }
 
        function callBack() {
            if (xmlReq.readyState == 4) {
                if (xmlReq.status == 200) {
                    alert(xmlReq.responseText); // 接收文本
                }
                else if (xmlReq.status == 404) {
                    alert("Requested URL is not found.");
                } else if (xmlReq.status == 403) {
                    alert("Access denied.");
                } else
                    alert("status is " + xmlReq.status);
            }
        }
 
    </script>
 
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input id="txtOldPwd" type="text" onblur="validateOldPwd(this)" />
    </div>
    </form>
</body>
</html>

  

分析:
a、以前我们通常都是通过一个简单的aspx文件实现的功能,其实通过ashx也可以。
笔者曾经写过的一篇ajax:数据传输方式简介 ,通过对比,我们发现aspx要将前后台显示和处理逻辑分开,所以就弄成了两个文件,其实,在最终编译的时候,aspx和cs还是会编译到同一个类中去.这中间就要设计html的一些逻辑处理;而ashx不同,它只是简单的对web http请求的直接返回你想要返回的结果.比aspx少处理了html的过程(但是ashx也可以处理html的一些逻辑,只是通常都不这么用)。理论上ashx比aspx要快。
b、还是在相同的旧文里,我们知道数据传输的几种方式,其实ashx都可以实现(修改ashx文件里context.Response.ContentType 即可),这里不再赘述了。
(2)、ashx特别适合于生成动态图片,生成动态文本(纯文本,json,xml,javascript等即可)等。 
(3)、.ashx文件有个缺点:它处理控件的回发事件非常麻烦。处理数据的回发,通常都需要一些.aspx页的功能,只有自己手动处理这些功能(还不如直接建一个aspx文件来处理)。所以,一般使用.ashx输出一些不需要回发处理的项目即可。

posted @   yinghualeihenmei  阅读(47)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示