Asp. NET operating mechanism of the general Processing program (ASHX)

Source: Internet
Author: User

I. Overview

Create a new Ashx file code as 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;}}    }

Two. Parsing

1).

<%@ WebHandler language= "C #" class= "Testhandler"  %>

@WebHandler specifies an HTTP handler file (. ashx) definition attribute (Attribute) and compilation options for an ASP.

Properties
class specifies an inheritance from IHttpHandler, which is instantiated to respond to requests when handler is requested. This attribute is required.
CODEBEHIND specifies the class corresponding to the file, basically useless, mainly used to support vs display, can be removed.

compilation options
Debug default is False, so non-debugging will not open, affect performance, you can omit
Description a description of the current handler, ASP. NET parsing, may provide auxiliary information when debugging, can omit
Language default C #, you can omit
WarningLevel 0-4 has a default value, which can be omitted.

2).

Next is the class created below

A key interface is implemented: System.Web.IHttpHandler. Implement it to indicate how the request from the outside will be handled.

Parameter context is System.Web.HttpContext type

The context object provides the internal server objects that are used to serve HTTP requests (such as request, Response,

Session and server), which can also access several of our large server objects.

You can write the details of how the request is handled in the ProcessRequest method

<%@ WebHandler language= "C #" class= "ImageHandler"%>using system;using system.web;///<summary>/// This is a generic handler that does not have any implementations. </summary>public class Imagehandler:ihttphandler {public        void ProcessRequest (HttpContext context)    {        //Gets the physical path of the virtual directory.         string path = context. Server.MapPath ("");        Gets the binary data for the picture file.        byte[] datas = System.IO.File.ReadAllBytes (path +     http://www.cnblogs.com/dongpo888/admin/file:////123.jpg );       Writes the binary data to the output stream.        context. Response.OutputStream.Write (datas, 0, Datas. Length);    }     public bool IsReusable     {        get {            return false;}}    }

IsReusable Indicates whether an instance of this class can be used by other requests.

The advantage of using ASHX is that you do not need to configure in Web. config to process requests directly with IHttpHandler derived classes.

Common scenarios: Generate images dynamically (such as CAPTCHA), respond to Ajax requests, and more.

Three. aspx, ascx, and ashx

Summary of use of Aspx,ascx and ashx

Doing ASP. Aspx,.ascx and. Ashx are not unfamiliar. About them, there are many articles on the web. "On paper to get the final feeling shallow, know this matter to preach", the following oneself summarizes to make a note.
1,. aspx
Web Forms design page. A Web Forms page consists of two parts: visual elements (HTML, server controls, and static text) and the programming Logic of the page (the Design view and code view in VS can see their corresponding files respectively). VS stores the two components separately in a separate file. Visual elements are created in the. aspx file.
2,. ascx
The user control for ASP. NET is developed as a Web page that encapsulates specific functionality and behavior, both of which are used on various pages of a Web application. A user control contains a combination of HTML, code, and other Web or user controls and is saved on the Web server in its own file format with the extension *.ascx. The default configuration in ASP. NET does not allow Web clients to access these files through URLs, but other pages of this site can integrate the features contained in these files.
3,. ashx
The first two are too familiar, this is the point to talk about.
(1), use example
The. ashx file is primarily used to write Web handler. Using the. ASHX allows you to focus on programming without the need for related web technologies. What we know about. aspx is to do HTML control tree parsing, and. aspx contains all the HTML that is actually a class, and all of the HTML is a member of the class, and this process is not needed in. ashx. The ashx must contain the IsReusable attribute (this property represents whether it is reusable, usually true), and the IRequiresSessionState interface must be implemented if you want to use the session with the Ashx file.
An example of a simple implementation that modifies the login user password:


<!--<br/><br/>code highlighting produced by Actipro Codehighlighter (freeware) <br/>http://www. codehighlighter.com/<br/><br/>-->using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using System.Web.Security;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Web.UI.WebControls.WebParts;
Using System.Web.UI.HtmlControls;
Using System.Web.SessionState;

Namespace Test
{

public class Handlertest:ihttphandler, IRequiresSessionState
{

public void ProcessRequest (HttpContext context)
{
Context. Response.clearcontent ();
Context. Response.ContentType = "Text/plain";
Context. Response.Cache.SetCacheability (Httpcacheability.nocache); No cache

String action = context. Request.params["Action"]; External request
if (action = = "Modifypwd")//user Change Password
{
String oldpwd = context. request.params["PWD"];

The IRequiresSessionState interface must be implemented in the ASHX file using the session
session["Logeduser"] is the session of the logged-on user, both the user name and the password are test
if (Oldpwd.toupper ()! = (context. session["Logeduser") as Customer). Password.toupper ())//The old password entered by the user is not the same as the current logged-on user
{
Context. Response.Write ("Old password input error!");
}
Else
{
Context. Response.Write ("Old password entered correctly!");
}
}


Context. Response.End ();
}

public bool IsReusable
{
Get
{
return true;
}
}
}
}

Client invocation (JS and page parts):


<!--<br/><br/>code highlighting produced by Actipro Codehighlighter (freeware) <br/>http://www. codehighlighter.com/<br/><br/>--><%@ page language= "C #" autoeventwireup= "true" CodeBehind= " ASHXTest.aspx.cs "inherits=" Ashxtest "%>

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<title>mytest</title>
<script type= "Text/javascript" >
function $ (s) {if (document.getElementById) {return eval (' document.getElementById ("' + S + ') ');} else {return eval (' document.all. ' + s);}}

function Createxmlhttp () {
var xmlHttp = false;
var arrsignatures = ["MSXML2. xmlhttp.5.0 "," MSXML2. Xmlhttp.4.0 ",
"MSXML2. xmlhttp.3.0 "," MSXML2. XMLHTTP ",
"Microsoft.XMLHTTP"];
for (var i = 0; i < arrsignatures.length; i++) {
try {
XmlHttp = new ActiveXObject (arrsignatures[i]);
return xmlHttp;
}
catch (Oerror) {
XmlHttp = false; Ignore
}
}
throw new Error ("MSXML is not installed on your system.");
if (!xmlhttp && typeof XMLHttpRequest! = ' undefined ') {
XmlHttp = new XMLHttpRequest ();
}
return xmlHttp;
}

var xmlreq = Createxmlhttp ();

Send AJAX processing request (here to simply verify the validity of the old password)
function Validateoldpwd (otxt) {
var url = "/handlertest.ashx?action=modifypwd&pwd=" + Escape (otxt.value); . ashx file
Xmlreq.open ("Get", url, True);
Xmlreq.setrequestheader ("If-modified-since", "0");
Xmlreq.onreadystatechange = CallBack;
Xmlreq.send (URL); Send text
}

function CallBack () {
if (xmlreq.readystate = = 4) {
if (Xmlreq.status = = 200) {
alert (Xmlreq.responsetext); Receive text
}
else if (xmlreq.status = = 404) {
Alert ("Requested URL is not found.");
} else if (xmlreq.status = = 403) {
Alert ("Access denied.");
} else
Alert ("Status is" + Xmlreq.status);
}
}

</script>

<body>
<form id= "Form1" runat= "Server" >
<div>
<input id= "Txtoldpwd" type= "text" onblur= "validateoldpwd (This)"/>
</div>
</form>
</body>

Analysis:
A, previously we are usually implemented through a simple ASPX file function, in fact, through the ashx can also.
The author has written an Ajax: Data transmission method Introduction, through comparison, we found that aspx to the front and back display and processing logic separate, so it made two files, in fact, in the final compilation, ASPX and CS will still be compiled into the same class. There is a need to design some logical processing of HTML, and unlike ASHX, it is simply a web The HTTP request directly returns the result that you want to return. The process of HTML is less processed than ASPX (but ashx can also handle some of the logic of HTML, which is not usually used). Theoretically ashx is faster than ASPX.
b, or in the same old text, we know several ways of data transmission, in fact ASHX can be implemented (modify the context in the Ashx file. Response.ContentType), here no longer repeat.
(2), ASHX is particularly suitable for generating dynamic images, generating dynamic text (plain text, json,xml,javascript, etc.).
(3),. ashx files have a drawback: it is cumbersome to handle postback events for controls. Processing the postback of the data usually requires the functionality of the. aspx pages, which are handled manually only by themselves (rather than by building an ASPX file directly). Therefore, it is generally used. ashx output some items that do not require postback processing.
4. Summary
Aspx-->p (Page)
Ascx-->c (Control)
Ashx-->h (HttpHandler)

When the browser accesses the Web server, we end up receiving HTML text. The browser interprets these labels through the rendering engine, showing the visible effect on the screen. and ASP. NET is a platform technology that we apply to "disguised" to explain the HTML, it is to improve productivity, it is more technical terminology, Essentially something in the HTML category (if you're not using the dynamic page technology to make full use of HTML and browser (including JS) technology to achieve dynamic page effects, Then you will find that the effect has a considerable amount of code. So the bottom of web development is a bunch of HTML tags, whether it is an ASP or JSP is a way of HTML packaging, is the product of HTML.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.