ashx文件

来源:互联网 发布:樊京辉 知乎 编辑:程序博客网 时间:2024/05/17 08:07

ashx是什么文件,如何创建 .ashx 文件用于写web handler的。其实就是带HTMLC#的混合文件。当然你完全可以用.aspx 的文件后缀。使用.ashx 可以让你专注于编程而不用管相关的WEB技术。.ashx必须包含IsReusable. 如下例所示


<% @ webhandler language="C#" class="AverageHandler" %>

using System;
using System.Web;

public class AverageHandler : IHttpHandler
{
public bool IsReusable
{ get { return true; } }
public void ProcessRequest(HttpContext ctx)
{
ctx.Response.Write("hello");
}
}.ashx
.aspx的好处在与不用多一个html// ----------------------------------------
// Pick your favorite image format
// ------------------------------
byte[]   byteArr = (byte[]) oChartSpace.GetPicture ("png", 500, 500);
// ----------------------------------------
// Store the chart image in Session to be picked up by an HttpHandler later
// ---------------------------------------
HttpContext      ctx = HttpContext.Current;
string           chartID = Guid.NewGuid ().ToString ();
           
ctx.Session [chartID] = byteArr;
imgHondaLineup.ImageUrl = string.Concat ("chart.ashx?", chartID);

chart.ashx里面就下面一句话

<% @ WebHandler language="C#" class="AspNetResources.Owc.ChartHandler" codebehind="chart.ashx.cs" %>

其实也可以用这个代替

web.config里面的<system.web>里面加上

<httpHandlers>
   <add verb="*" path="*.ashx" type="AspNetResources.Owc, ChartHandler " validate="false" /> /*ChartHandler  
是那个ashx.cs编译后生成的代码Assembly*/
  
   <!--Since we are grabbing all requests after this, make sure Error.aspx does not rely on .Text -->
   <add verb="*" path="Error.aspx" type="System.Web.UI.PageHandlerFactory" />
  

</httpHandlers>

具体使用哪个都无所谓,后一种配置好了就方便一些,不用管路径了,其实这个思想的应用比较知名的在.text里面就已经有了,只不过应用的方向不同。

ashx.cs文件的代码

using System;
using System.Web.SessionState;
using System.IO;
using System.Web;

namespace AspNetResources.Owc
{
public class ChartHandler : IHttpHandler, IReadOnlySessionState
{
         public bool IsReusable
         {
             get { return true; }
         }
   
         public void ProcessRequest (HttpContext ctx)
         {
             string chartID = ctx.Request.QueryString[0];
             Array arr = (Array) ctx.Session [chartID];

             ctx.ClearError ();
             ctx.Response.Expires = 0;
             ctx.Response.Buffer = true;
             ctx.Response.Clear ();

             MemoryStream memStream = new MemoryStream ((byte[])arr);
             memStream.WriteTo (ctx.Response.OutputStream);
             memStream.Close ();

             ctx.Response.ContentType = "image/png";
             ctx.Response.StatusCode = 200;
             ctx.Response.End ();

         }
     }
}

 
原创粉丝点击