IHttpModule和IHttpHandler 應用筆記
關於HttpModule的註冊、應用方法請參看我的另一篇博文:
關於IHttpHandler的應用,我們先從它的註冊方法講起。
當你建立了一個實現了Ihttphandler介面的類後,可以在網站的web.config檔案中註冊這個httphandler
示例如下:
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="*" path="*.ho" type="WebApplication2.HelloHandler,WebApplication2"/>
httpHandlers>
其中最後一行 <add verb="*" path="*.ho" type="WebApplication2.HelloHandler,WebApplication2"/>
便是我們手工加入的內容,WebApplication2.HelloHandler是實現了IhttpHandler介面的一個類,Path屬性表示的是對映的檔案格式。
這樣註冊好之後,如果從網站請求任何帶字尾名.ho的檔案時,就會轉到WebApplication2.HelloHandler類進行處理。
而WebApplication2.HelloHandler的內容可以是在網頁上列印一行文字(如下面程式碼),也可以是下載一個檔案,反正在httphandler裡面你可以控制response物件的輸出。
下面程式碼示例列印一行文字的WebApplication2.HelloHandler原始碼:
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
namespace WebApplication2
{
public class HelloHandler:IHttpHandler
{
#region IHttpHandler
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html";
context.Response.Write("");
context.Response.Write("");
context.Response.Write("Response by HelloHandler!");
context.Response.Write("");
context.Response.Write("");
}
public bool IsReusable
{
get
{ return true; }
}
#endregion
}
}
以下內容為轉載的IhttpHandler示例:利用IhttpHandler實現檔案下載
1. 首先新建一個用於下載檔案的page頁,如download.aspx,裡面什麼東西也沒有。
2. 新增一個DownloadHandler類,它繼承於IHttpHandler介面,可以用來自定義HTTP 處理程式同步處理HTTP的請求。
using System;
using System.IO;
public class DownloadHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
HttpResponse Response = context.Response;
HttpRequest Request = context.Request;
System.IO.Stream iStream = null;
byte[] buffer = new Byte[10240];
int length;
long dataToRead;
try
{
string filename = FileHelper.Decrypt(Request["fn"]); //通過解密得到檔名
string filepath = HttpContext.Current.Server.MapPath("~/") + "files/" + filename; //待下載的檔案路徑
iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,
System.IO.FileAccess.Read, System.IO.FileShare.Read);
Response.Clear();
dataToRead = iStream.Length;
long p = 0;
if (Request.Headers["Range"] != null)
{
Response.StatusCode = 206;
p = long.Parse(Request.Headers["Range"].Replace("bytes=", "").Replace("-", ""));
}
if (p != 0)
{
Response.AddHeader("Content-Range", "bytes " + p.ToString() + "-" + ((long) (dataToRead - 1)).ToString() + "/" + dataToRead.ToString());
}
Response.AddHeader("Content-Length", ((long) (dataToRead - p)).ToString());
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(System.Text.Encoding.GetEncoding(65001).GetBytes(Path.GetFileName(filename))));
iStream.Position = p;
dataToRead = dataToRead - p;
while (dataToRead > 0)
{
if (Response.IsClientConnected)
{
length = iStream.Read(buffer, 0, 10240);
Response.OutputStream.Write(buffer, 0, length);
Response.Flush();
buffer = new Byte[10240];
dataToRead = dataToRead - length;
}
else
{
dataToRead = -1;
}
}
}
catch (Exception ex)
{
Response.Write("Error : " + ex.Message);
}
finally
{
if (iStream != null)
{
iStream.Close();
}
Response.End();
}
}
public bool IsReusable
{
get { return true; }
}
}
3. 這裡涉及到一個檔名加解密的問題,是為了防止檔案具體名稱暴露在狀態列中,所以新增一個FileHelper類,程式碼如下:
{
public static string Encrypt(string filename)
{
byte[] buffer = HttpContext.Current.Request.ContentEncoding.GetBytes(filename);
return HttpUtility.UrlEncode(Convert.ToBase64String(buffer));
}
public static string Decrypt(string encryptfilename)
{
byte[] buffer = Convert.FromBase64String(encryptfilename);
return HttpContext.Current.Request.ContentEncoding.GetString(buffer);
}
}
利用Base64碼對檔名進行加解密處理。
4. 在Web.config上,新增httpHandlers結點,如下:
<httpHandlers>
<add verb="*" path="download.aspx" type="DownloadHandler" />
httpHandlers>
system.web>
5. 現在新建一個aspx頁面,對檔案進行下載:
Default.aspx程式碼如下:
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
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>檔案下載title>
head>
<body>
<form id="form1" runat="server">
<div>
<asp:HyperLink ID="link" runat="server" Text="檔案下載">asp:HyperLink>
div>
form>
body>
html>
Default.aspx.cs程式碼如下:
using System.Data;
using System.Configuration;
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;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string url = FileHelper.Encrypt("DesignPattern.chm");
link.NavigateUrl = "~/download.aspx?fn=" + url;
}
}
這樣就實現了檔案下載時,不管是什麼格式的檔案,都能夠彈出開啟/儲存視窗。
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/12639172/viewspace-616536/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- IHttpModule與IHttpHandler的區別(續)HTTP
- IHttpModule介面HTTP
- this和super的區別和應用 學習筆記筆記
- ChartDirector應用筆記(一)筆記
- ChartDirector應用筆記(二)筆記
- ChartDirector應用筆記(三)筆記
- 淺談IHttpHandlerHTTP
- TRIZ——物理矛盾應用筆記筆記
- 快應用入門筆記筆記
- es6筆記應用 二筆記
- es6筆記應用一筆記
- 《WEB應用測試》筆記(五)Web筆記
- Tea,為 hacker 而生的筆記應用筆記
- Android應用開發筆記(一)Android筆記
- 馬克筆記—Android 端開源的 Markdown 筆記應用筆記Android
- Adaptive AUTOSAR 學習筆記 7 - 應用設計和 ManifestAPT筆記
- 《Redis深度歷險:核心原理和應用實踐》讀書筆記Redis筆記
- ThreadX應用筆記:核心初始化和任務排程thread筆記
- Kinect開發學習筆記之(一)Kinect介紹和應用筆記
- Laravel 原始碼筆記 應用程式 ApplicationLaravel原始碼筆記APP
- Electron+GithubAPI打造個人筆記應用GithubAPI筆記
- Angular做一個筆記文章管理應用Angular筆記
- 計算機網路-應用層筆記計算機網路筆記
- 資料結構筆記-棧的應用資料結構筆記
- jsp應用開發詳解筆記JS筆記
- IOS開發筆記之應用間的跳轉和資料傳遞iOS筆記
- 筆記-iOS應用程式的啟動過程筆記iOS
- Redis In Action 筆記(五):使用 Redis 支援應用程式Redis筆記
- 「構建安全的 PHP 應用」讀書筆記PHP筆記
- 【筆記】遍歷二叉樹的應用筆記二叉樹
- 『應用機器學習的建議』的學習筆記機器學習筆記
- 大型資料庫應用——一些筆記資料庫筆記
- Kubernetes學習筆記(六):使用ConfigMap和Secret配置應用程式筆記
- 利用IhttpHandler實現檔案下載HTTP
- oracle學習筆記(十七) PL/SQL高階應用Oracle筆記SQL
- 熱更新應用--熱補丁Hotfix學習筆記筆記
- Flutter 學習筆記(一):第一個 Flutter 應用Flutter筆記
- 演算法學習筆記(2): 逆元及其應用演算法筆記