天天看點

aspx,ascx和ashx使用小結

做asp.net開發的對.aspx,.ascx和.ashx都不會陌生。關于它們,網上有很多文章介紹。“紙上得來終覺淺,絕知此事要躬行”,下面自己總結一下做個筆記。

1、.aspx

Web窗體設計頁面。Web窗體頁由兩部分組成:視覺元素(html、伺服器控件和靜态文本)和該頁的程式設計邏輯(VS中的設計視圖和代碼視圖可分别看到它們對應得檔案)。VS将這兩個組成部分分别存儲在一個單獨的檔案中。視覺元素在.aspx 檔案中建立。

2、.ascx

asp.net的使用者控件,是作為一種封裝了特定功能和行為(這兩者要被用在Web應用程式的各種頁面上)的Web頁面被開發的。一個使用者控件包含了html、代碼和其他Web或者使用者控件的組合,并在Web伺服器上以自己的檔案格式儲存,其擴充名是*.ascx。asp.net裡的預設配置并不允許Web用戶端通過url來通路這些檔案,但是這個網站的其他頁面可以內建這些檔案裡所包含的功能。

3、.ashx

前面兩個都太熟悉了,這個才是要講的重點。

(1)、使用舉例

.ashx檔案是主要用來寫web handler的。使用.ashx 可以讓你專注于程式設計而不用管相關的web技術。我們熟知的.aspx是要做html控件樹解析的,.aspx包含的所有html實際上是一個類,所有的html都是類裡面的成員,這個過程在.ashx是不需要的。ashx必須包含IsReusable屬性(這個屬性代表是否可複用,通常為true),而如果要在ashx檔案用使用Session必須實作IRequiresSessionState接口.

一個簡單的實作修改登入使用者密碼的示例:

aspx,ascx和ashx使用小結

Code

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和頁面部分):

aspx,ascx和ashx使用小結

<%@ 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輸出一些不需要回發處理的項目即可。

4、總結

aspx-->P(Page)