1、Request
下面做一個執行個體,通過Request的一些方法來判斷瀏覽圖片是不是在內部瀏覽,還是直接按網址瀏覽或者被外部使用
1 <%@ WebHandler Language="C#" Class="image_Test" %> 2 3 using System; 4 using System.Web; 5 6 public class image_Test : IHttpHandler { 7 8 public void ProcessRequest(HttpContext context) 9 {10 context.Response.ContentType = "image/JPEG";11 //如果直接存取URLreferrer 就是null ,如果嵌入到頁面中請求12 //URLreferrer就是頁面的地址13 string picPath=HttpContext.Current.Server.MapPath("DSCF0738.JPG");14 using (System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(picPath)) {15 using (System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(bitmap)) 16 {17 //不過還是太脆弱,因為UrlReferrer還是由用戶端提交18 //迅雷破解毫無鴨梨19 if (context.Request.UrlReferrer == null)20 {21 graphic.Clear(System.Drawing.Color.White);22 graphic.DrawString("禁止直接瀏覽圖片", new System.Drawing.Font("宋體", 15),23 System.Drawing.Brushes.Red, 0, 0);24 25 }26 //http://127.0.0.1:32581/WebSite_zzl01/vivideo_test/request/Request.aspx27 28 else if (context.Request.UrlReferrer.Host != "localhost")29 {30 graphic.Clear(System.Drawing.Color.White);31 graphic.DrawString("圖片只允許在部落格園內部查看", new System.Drawing.Font("宋體", 15),32 System.Drawing.Brushes.Red, 0, 0);33 }34 //轉化成流格式輸出35 bitmap.Save(context.Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg);36 37 }38 }39 }40 41 public bool IsReusable {42 get {43 return false;44 }45 }46 47 }
html
<img src="image_Test.ashx" />啦啦啦啦
2、Response
(1)返回 流,以流的形式返回給用戶端
* 每次write,往緩衝裡存,不是直接給瀏覽器,等到存滿了或者處理完成才發送到瀏覽器
* Flush方法,立即發給瀏覽器
(2)反盜鏈等:不往下執行了在aspx寫較好
context.Response.End();
(3)aspx 和ashx
像輸出文本、圖片、最後是寫在ashx裡面,而html內容則寫在aspx裡面
(4)重新導向 Redirect
Flush執行個體:
<%@ WebHandler Language="C#" Class="response" %>using System;using System.Web;public class response : IHttpHandler { public void ProcessRequest (HttpContext context) { //如果是plain則<br/>無效果 context.Response.ContentType = "text/html"; //耗時操作 for (int i = 0; i < 20; i++) { System.Threading.Thread.Sleep(500); context.Response.Write("第"+i+"步開始執行<br/>"); //採用Flush,立即發給用戶端,效果很明顯! context.Response.Flush(); } } public bool IsReusable { get { return false; } }}
3、server
(1)Server.Transfer和 Response.Redirect的區別
*transfer訪問只能是內部網站,不能是外部的,而redirect可以
* transfer是網站內部接管的,只執行一次http請求,而Redirect則是轉幾次就執行幾次http請求並在地址欄中顯示
* transfer會直接把各種資訊傳過去而Redirect不會
* 不能重新定向到ashx transfo
執行個體:
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;public partial class vivideo_test_server_server : System.Web.UI.Page{ protected void Page_Load(object sender, EventArgs e) { string text=Request["id"]; if (text == "1") { Response.Write("一"); } else if(text=="2"){ //請求的資訊都會傳入伺服器 Server.Transfer("DSCF0738.JPG"); } else if (string.IsNullOrEmpty(text)) { Response.Write("空"); } else { //不會取到傳過來的參數 Response.Redirect("蘋果.jpg"); //除非自己給它穿過去 //Response.Redirect("aaa.aspx?id=1"); } }}