I. Overview
Create an ashx FileCodeAs follows:
<% @ Webhandler Language = "C #" Class = "Testhandler" %> Using System; Using System. Web; Public class Testhandler : Ihttphandler {// Dd Public void Processrequest ( Httpcontext Context) {context. response. contenttype = "Text/plain" ; Context. response. Write ( "Hello World" );} // Dd Public bool Isreusable { Get { Return false ;}}}
Ii. Analysis
1 ).
<%@WebhandlerLanguage= "C #"Class= "Testhandler"%>
@ Webhandler: Specifies an instruction for an ASP. NET page as an HTTP handler file (. ashx) to define attributes and compilation options.
Attribute
Class specifies a class that inherits from ihttphandler. When handler is requested, it is instantiated to respond to the request. This attribute is required
Codebehind specifies the file corresponding to the class, which is basically useless. It is mainly used to support vs display and can be removed.
Compilation options
The default value of DEBUG is false, so you do not need to enable debug without debugging. This may affect performance and can be omitted.
Description about the current handler, which is ignored during ASP. NET parsing. It may provide auxiliary information during debugging and can be omitted.
Language: C # by default, which can be omitted.
WarningLevel 0-4 has the default value, which can be omitted.
2 ).
Next is the class created below
A key interface is implemented: system. Web. ihttphandler. Implementation indicates the method in which requests from external sources will be processed.
The context parameter is of the system. Web. httpcontext type.
The context object provides internal server objects (such as request, response,
Session and server), that is, you can access several of our server objects.
You can write the request details in the processrequest method.
<% @ Webhandler Language = "C #" Class = "Imagehandler" %> Using System; Using System. Web; /// <Summary> /// This is a general process without any implementation.Program. /// </Summary> Public class Imagehandler :Ihttphandler { Public void Processrequest ( Httpcontext Context ){ // Obtain the physical path of the virtual directory. String Path = context. server. mappath ( "" ); // Obtain the binary data of the image file. Byte [] Datas = system. Io. File . Readallbytes (path + HTTP: // Www.cnblogs.com/dongpo888/admin/file:///123.jpg ); // Write binary data to the output stream. Context. response. outputstream. Write (datas, 0, datas. Length );} Public bool Isreusable { Get { Return false ;}}}
Isreusable indicates whether other requests can use an instance of this class.
The advantage of using ashx is that you can directly use the ihttphandler derived class to process requests without configuring in Web. config.
Common application scenarios: dynamically generate images (such as verification codes) and respond to Ajax requests.
Iii. aspx, ascx, and ashx
Refer to the following blog
Click link