2010-02-25 15 views

回答

5

通用處理程序是實現System.Web.IHttpHandler接口的.NET組件。任何實現IHttpHandler接口的類都可以充當傳入HTTP請求的目標。頁面也是通用處理程序。通常,通用處理程序具有ASHX的擴展。

你可以找到例子here

2

一些ASP.NET文件是動態生成的。它們是用C#代碼或磁盤資源生成的。這些文件不需要Web窗體。相反,ASHX通用處理程序是理想的。它可以動態地從查詢字符串返回圖像,寫入XML或任何其他數據。

1

Ashx文件不過是一個aspx頁面。它們相當於用C Sharp或Visual Basic.NET編寫的自定義處理程序,它們包含完全實現IHttpHandler的類。與ASPX文件相同,它們非常方便。你只需瀏覽他們,他們就會自動編譯。

當使用

簡單的HTML頁面
Asp.net自定義的WebForms(ASPX)控制
簡單Dyanamic頁面

當解毒(ASHX)使用

二進制文件
動態圖像視圖
性能關鍵網頁
個XML文件
最少的Web頁

0

ASHX通用處理器是返回動態內容的概念。它用於返回ajax調用,查詢字符串中的圖像,寫入XML或任何其他數據。 我用它從查詢字符串中返回MP4文件。請找到下面的代碼。

using System; 
using System.Collections.Generic; 
using System.Configuration; 
using System.Data.SqlClient; 
using System.Linq; 
using System.Web; 
namespace ESPB.CRM.Web.UI.VideoUploading 
{ 

public class FileCS : IHttpHandler 
{ 

    public void ProcessRequest(HttpContext context) 
    { 
     int id = int.Parse(context.Request.QueryString["id"]); 
     byte[] bytes; 
     string contentType; 
     string strConnString = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString; 
     string name; 
     using (SqlConnection con = new SqlConnection(strConnString)) 
     { 
      using (SqlCommand cmd = new SqlCommand()) 
      { 
       cmd.CommandText = "select Name, Data, ContentType from VideoUpload where [email protected]"; 
       cmd.Parameters.AddWithValue("@Id", id); 
       cmd.Connection = con; 
       con.Open(); 
       SqlDataReader sdr = cmd.ExecuteReader(); 
       sdr.Read(); 
       bytes = (byte[])sdr["Data"]; 
       contentType = sdr["ContentType"].ToString(); 
       name = sdr["Name"].ToString(); 
       con.Close(); 
      } 
     } 
     context.Response.Clear(); 
     context.Response.Buffer = true; 
     context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + name); 
     context.Response.ContentType = contentType; 
     context.Response.BinaryWrite(bytes); 
     context.Response.End(); 
    } 

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

在這裏,我已經創建FileCS.ashx文件。 我在哪裏繼承IHttpHandler接口。並編寫ProcessRequest(HttpContext上下文)函數,該函數在調用文件時將運行默認值。而context.Request.QueryString []將獲得參數。在這裏,我通過id作爲參數。 IsReusable()函數可以用於良好的性能。

相關問題