ASP.NET ASHX Handler

Some ASP.NET files are dynamic. They are generated with C# code or disk resources. These files do not require web forms. Instead, an ASHX generic handler is ideal. It can return an image from a query string, write XML, or any other data.

Tutorial

First, we review the goal of using ASHX files in the ASP.NET web development framework. We use the ASHX file in a URL, and have it dynamically return content. We will use the query string. The final URLs will look like this.

Url example

http://www.dotnetperls.com/?file=name

Getting started. We list the steps to add a new ASHX file. To do this, open your ASP.NET web site. Go to the Website menu and click on the first menu item there, "Add New Item...". This will present the Add New Item dialog box.

Then:Select the "Generic Handler" item, and you will get a new file with some code in it called Handler.ashx.

Autogenerated code

What purpose does the autogenerated code in the ASHX file have? It defines two parts of the IHttpHandler interface. The important part is ProcessRequest(), which will be invoked whenever the Handler.ashx file is requested.

Tip:You should not change the interface inheritance or remove either of the members.

Mappings

It is often desirable to map an older URL or path to your new ASHX file. For backwards compatibility and for search engine optimization, you will probably want the new handler to take over an old URL in your site.

Tip:To do this, use urlMappings. Alternatively you can use more complex RewritePath methods.

Part of Web.config file: XML

<system.web>
    <urlMappings enabled="true">
	<add url="~/Default.aspx" mappedUrl="~/Handler.ashx"/>
    </urlMappings>
    ...

URL mappings. The above Web.config markup will automatically link one URL to another. When the Default.aspx page is requested, your Handler.ashx file will take over. This means you can map the default page in a directory to your handler.

urlMappings for Redirects

Add example image

We mention what you can do with the ASHX file involving images. Find your favorite image on your disk or on the Internet and add it to your website project. For my example, the image I chose was "Flower1.png".

Next:We will use this image in the Handler.ashx file. We implement an image-based handler.

Modify Handler.ashx

Your handler has two parts. Here we modify the ProcessRequest method. We can change the ContentType of the file and the Response content. Modify your Handler.ashx to be similar to the following, with your image ContentType and file name.

ASHX code-behind file: C#

<%@ WebHandler Language="C#" class="Handler" %>

using System;
using System.Web;

public class Handler : IHttpHandler {

    public void ProcessRequest (HttpContext context) {
	// Comment out these lines first:
	// context.Response.ContentType = "text/plain";
	// context.Response.Write("Hello World");

	context.Response.ContentType = "image/png";
	context.Response.WriteFile("~/Flower1.png");
    }

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

Test handler

Here we test the new configuration and ASHX file on the local machine. Now click the green arrow to run your website on the development server. You should see the image in your browser. This is the result of the handler.

Add functionality

The example here so far is relatively useless. All it does is allow us to pipe an image through an ASHX handler. You can add any functionality (logging code or referrer logic) to the handler in the C# language.

Also, developers commonly need to use the QueryString collection on the Request. You can use the Request.QueryString in the Handler just like you would on any ASPX web form page. The code is the same.

ASHX modified code-behind: C#

<%@ WebHandler Language="C#" class="Handler" %>

using System;
using System.Web;

public class Handler : IHttpHandler {

    public void ProcessRequest (HttpContext context) {

	HttpResponse r = context.Response;
	r.ContentType = "image/png";
	//
	// Write the requested image
	//
	string file = context.Request.QueryString["file"];
	if (file == "logo")
	{
	    r.WriteFile("Logo1.png");
	}
	else
	{
	    r.WriteFile("Flower1.png");
	}
    }

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

What this does. The above code receives requests and then returns a different file based on the QueryString collection value. It will return one of two images from the two query strings. The strings it returns are shown.

URL 1

	      URL: http://www.dotnetperls.com/?file=logo
File query string: logo
     File written: Logo1.png

URL 2

	      URL: http://www.dotnetperls.com/?file=flower
File query string: flower
     File written: Flower1.png

Test query string

Does all this work? Yes, but it is always important to test. Open your browser. And on the path, add query strings like those shown above. What happens is that ASP.NET internally maps the Default.aspx page to your Handler.ashx.

Then:The Handler.ashx file receives the query string and writes the appropriate file.

Uses

The code here could be used as a hit tracker that counts visitors and logs referrers. This could provide a more accurate visit count than server logs, because of browser and bot differences.

Handlers versus web pages. ASP.NET web forms inherit from the Page class. This provides them with many events and a detailed initialization and event model. You don‘t need that for dynamic images, XML, or binary files.

Image Output

Performance

Is there any performance advantage or change to using ASHX files? These files are less complex and they do not involve as many events. They are more streamlined and involve less code, and this is an advantage.

As you can imagine, firing more than ten events each time a request is handled is a fair amount more expensive than only firing one event. Therefore, there will be some performance advantage to using ASHX files where possible.

IsReusable:I do not know precisely what the IsReusable property does. Much of the supporting code is not in the ASHX file itself.

But:My reading indicates it can improve performance and decrease memory pressure by not repeatedly destroying the handler.

Choose handlers

Here I want to propose some guidelines about when to choose custom handlers and when to prefer ASPX web form pages. Handlers are better for binary data, and web forms are best for rapid development.

Use Web Forms...

If you have simple HTML pages
ASP.NET custom controls
Simple dynamic pages

Use handlers...

If you have binary files
Dynamic image views
Performance-critical web pages
XML files
Minimal web pages

Control trees

In the ASP.NET Framework, web forms use a concept called control trees where the parts of web pages are stored in an object model. Use custom handlers when you do not require the custom control tree or the whole HTML web form framework.

Note:This will result in greater performance. And the code will be much simpler code to debug.

Summary

We used ASHX custom handlers in an ASP.NET website. This could fill many different important web site functions. We combine urlMappings with query strings on custom handlers to greatly simplify and streamline back-end web site code.

【转载】http://www.dotnetperls.com/ashx

时间: 2024-10-13 18:22:56

ASP.NET ASHX Handler的相关文章

[asp.net]ashx中session存入,aspx为null的原因(使用flash uploader)

I am using uploadify to upload files, they automatically post to the handler. I then modify the session in the handler that I have setup as a static property in a common class of the website. I then try to access that same session in the aspx page, a

asp.net .ashx,cs文件使用server.mappath解决方法

asp.net .ashx文件使用server.mappath解决方法: System.Web.HttpContext.Current.Server.MapPath 在类文件中使用: System.Web.HttpServerUtility server = System.Web.HttpContext.Current.Server;server.MapPath(...)

asp.net 通过 Handler 导出数据至excel (让用户下载)

效果图: 代码: Export2Excel.ashx 1 <%@ WebHandler Language="C#" CodeBehind="Export2Excel.ashx.cs" Class="BLIC.SecurityCodeValidate.Web.Handler.Export2Excel" %> Export2Excel.ashx.cs 1 using System; 2 using System.Collections.G

Echarts 使用asp.net +ashx+ajax 实现 饼图、柱形图后台交互

向上效果图 前端code /* * ------------------------------------------------------------------ * module-information: * ------------------------------------------------------------------ * create * @date 2017-02-09 * @author vicm<[email protected]> * ---------

ASP.NET ashx实现无刷新页面生成验证码

现在大部分网站登陆时都会要求输入验证码,在网上也看了一些范例,现在总结一下如何实现无刷新页面生成验证码. 效果图: 实现方式: 前台: 1 <div> 2 <span>Identifying Code:</span> 3 <asp:TextBox ID="txtValidationCode" runat="server" Width="130px" MaxLength="4">&

ASP.NET ----ashx一般处理程序

asp.net中的一般处理程序,文件后缀为ashx. 代码示例: /// <summary> /// login 的摘要说明 /// </summary> public class login : IHttpHandler { public void ProcessRequest(HttpContext context) { //context.Response.ContentType = "text/plain"; //context.Response.Wri

ASP.NET ASHX中访问Session

默认,在ashx文件中无法使用Session,直接获取context.Session只能取得null. 解决办法: 添加命名空间 using System.Web.SessionState 的引用 让这个General Handler类实现IRequiresSessionState接口 然后再用context.Session或HttpContext.Current.Session就能获取Session

ASP.NET ASHX中获得Session的方法

1-在 aspx和aspx.cs中,都是以Session["xxx"]="aaa"和aaa=Session["xxx"].ToString()进行读写. 而在ashx中,Session都要使用context.Session,读写方法是这样的: context.Session["xxx"]="aaa"和aaa=context.Session["xxx"].ToString() 2-在ash

ASP.NET中使用JqGrid完整实现

文章提纲 介绍 & 使用场景 JqGrid的一些说明 JqGrid和ASP.NET整合详细步骤 前置准备 框架搭建 数据填充 数据增/删/改 其他 介绍&使用场景 JqGrid不是一个新鲜玩意,已经是一个久经证明的开源数据显示控件了. 园子里也有一些介绍文章,为什么还要写这篇文章呢? 因为还找不到可以完整讲述JqGrid集成的文章,我指的是从头至尾的完整的讲述,而不是其中一些片段或介绍一些参数. 正好在看到一篇文章完整的讲述了这个步骤: http://www.codeproject.com