ASP.NET 學習3_一般處理程序(泛型處理常式)_ashx檔案

泛型(一般)處理常式(程序)
所謂的泛型(HTTP)處理常式,白話來說就是一個不是
用來顯示畫面的網頁處理subruntime、方法,緊緊就
只是一個負責處理HTTP Request的處理程序(不包含weborm event life cyce),因此較輕量級。
實作了IHttpHandler的Interface,隸屬於web project,副檔名.ashx  (對專案右鍵新增...)
https://docs.microsoft.com/zh-tw/previous-versions/visualstudio/visual-studio-2008/bb398986(v=vs.90)?redirectedfrom=MSDN


優點:
不必繼承自Page Class (.aspx要),因此沒有這麼多事件
需執行,較不耗資源,性能比aspx優

缺點:
每一個頁面都需要寫對應一個對象的處理程序,因此檔案會較多。



微軟官方程式範例
https://docs.microsoft.com/zh-tw/dotnet/api/system.web.ihttphandler.processrequest?view=netframework-4.8#System_Web_IHttpHandler_ProcessRequest_System_Web_HttpContext_

 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
// Name this C# file HandlerTest.cs and compile it with the
// command line: csc /t:library /r:System.Web.dll HandlerTest.cs.
// Copy HandlerTest.dll to your \bin directory.

using System.Web;

namespace HandlerExample
{
   public class MyHttpHandler : IHttpHandler
   {
      // Override the ProcessRequest method.
      public void ProcessRequest(HttpContext context)
      {
         context.Response.Write("<H1>This is an HttpHandler Test.</H1>");      
         context.Response.Write("<p>Your Browser:</p>");
         context.Response.Write("Type: " + context.Request.Browser.Type + "<br>");
         context.Response.Write("Version: " + context.Request.Browser.Version);
      }

      // Override the IsReusable property.
      public bool IsReusable
      {
         get { return true; }
      }
   }
}

/*
______________________________________________________________

To use this handler, include the following lines in a Web.config file.

<configuration>
   <system.web>
      <httpHandlers>
         <add verb="*" path="handler.aspx" type="HandlerExample.MyHttpHandler,HandlerTest"/>
      </httpHandlers>
   </system.web>
</configuration>
*/

ProcessRequest
接收Request時候,就會觸發執行進來,跟aspx的Page_Load有點像。
參數是傳入HttpContext 物件(Http上下文)
HttpContext 物件,提供
對內建伺服器物件 (例如 Request、Response、Session 和 Server) 的參考,用來
服務 HTTP 要求。

支援Get/Post發出請求
Get -> 用 Request.QueryString["Key1"]接收
Post -> 用Request.Form["Key1"]接收
不曉得Get或Post就直接用Request["Key1"] ->Get,Post通用,但效率會差一點


【HTML Input版 搭配HTTP(泛型)處理常式/HTTP Handler】
我們用一個按下按鈕會自動累加(遞增1)的例子來分析
搭配泛型處理常式(HTTP Handler)
一個是html的檔案呈現User Interface
一個.ashx的檔案主要去處理form送出後的累加邏輯

示意

寫好的邏輯大致上是這樣
ViewStateTest1.html


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <form action="IncreaseHttpHandler.ashx">
        <input id="IsPostBack" name="IsPostBack" value="true" type="hidden" />
        <input id="txtNum" name="txtNum" value="@value" type="text" />
        <input id="btnSend" type="submit" value="遞增" />
    </form>
</body>
</html>


IncreaseHttpHandler.ashx


 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ViewStateExample1
{
    /// <summary>
    /// IncreaseHttpHandler 的摘要描述
    /// </summary>
    public class IncreaseHttpHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            string fullPath = context.Server.MapPath("ViewStateTest1.html");
            string webPageContent = System.IO.File.ReadAllText(fullPath);

            string IsPostBack = context.Request["IsPostBack"];
            string number = context.Request["txtNum"];

            if (IsPostBack =="true")
            {
                int n = Convert.ToInt32(number);
                n++;
                number = n.ToString();
            }
            else
            {
                number = "0";
            }
            webPageContent = webPageContent.Replace("@value", number);
            context.Response.Write(webPageContent);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

在執行請請到專案屬性硬性去設置啟始頁
指定為泛型處理常式

當啟動後的第一次就會呈現透過HttpHandler邏輯處理完的頁面
這裡在html中透過form搭配type為submit(不要搞混用成button)的 input  tag
去進行表單每次送出,觸發httphandler(.ashx)執行後端邏輯作用

一開始頁面呈現
表單Default 傳送會以Get方式(網址可看到傳送內容)觸發給它
 第一次按下遞增
 第二次按下遞增

這裡要注意像這種設計方式,通常此html檔案不會讓user可以巡覽的!!!!
因為真正動態效果進入點是透過泛型處理常式

泛型處理常式應用可參考另外一篇(透過WebRequest POST方式)
https://coolmandiary.blogspot.com/2020/01/aspnetwebformpost.html








留言

這個網誌中的熱門文章

經得起原始碼資安弱點掃描的程式設計習慣培養(五)_Missing HSTS Header

經得起原始碼資安弱點掃描的程式設計習慣培養(三)_7.Cross Site Scripting(XSS)_Stored XSS_Reflected XSS All Clients

(2021年度)駕訓學科筆試準備題庫歸納分析_法規是非題