Underlying principles of Asp. Net (II. Write your own Asp. Net Framework)

Source: Internet
Author: User

Write your own Asp.. Net Framework. We will not reference System. for the Web assembly, we only need to create a class library for ourselves. Therefore, in the next program, all the Web Components we use are defined by ourselves. First, create an Assembly named MyWebApplication and define the next HttpContext type. It encapsulates the context object. 1. HttpContext defines three attributes: The current server request -- HttpRequest Server Response -- HttpResponse: A "tool class" -- HttpServerUtility public class HttpContext {public HttpContext (string strRequest ); public HttpRequest Request {get;} public HttpResponse Response {get;} public HttpServerUtility Server {get; set ;}} is somewhat different from the real underlying layer. The real underlying layer is cumbersome in context encapsulation, of course it is powerful enough. Here, we will simply classify request packets and hand over the classified data results to HttpRequest for storage: The HttpRequest constructor accepts a request packet and intercepts and classifies the request packets, here we will only pick up two required data URLs and httpMethod. NameValueCollection is a set of dictionary types. It encapsulates Get Request data for different response data requests according to different parameters. queryString []. You are familiar with it. Public class HttpRequest {public HttpRequest (string strRequest); public string HttpMethod {get; set;} public NameValueCollection QueryString {get; set;} public string Url {get; set ;}} httpResponse provides the Write method, and the final output must be converted to byte bytes. The Write (stringresponseStr) method is to accumulate the output text and convert the output to byte bytes. The CreateResponseContent method integrates the Response Message (ResponseBody and ResponseHead) during output. Public class HttpResponse {public HttpResponse (HttpRequest request); public HttpRequest Request {get; set;} public byte [] ResponseBody {get;} public byte [] ResponseHeader {get; set ;} public void CreateResponseContent (); public void Write (byte [] B); public void Write (string responseStr);} HttpServerUtility provides a method to replace the Html template, ing the virtual path to the physical path under the Assembly: public class HttpServerUtility: MarshalByRe FObject {public HttpServerUtility (); public string MapPath (string path);} 2. The HttpApplication object constitutes Asp. net pipeline core object, the actual HttpApplication is created through reflection, and this method needs to be abstract a lot, we will introduce in the next article what is the actual HttpApplication. In our HttpApplication, 19 events are defined. HttpModule registers these events. The InitInternal method is the initialization method of HttpApplication. it is executed in the ProcessRequest method. In the InitInteranl method, an InitModules method is called to initialize all HttpModele. The ProcessRequest method is to bind and start executing all the events registered in the HttpModule, and create HttpHandler by reflection based on the request url path in the 7-8 events, the HttpHandler ProcessRequest method is executed in the 11-12 period. Public class HttpApplication: IHttpHandler {public HttpApplication (); public HttpContext Context {get; set;} public event EventHandler listener; public event EventHandler AunthorizeRequest; public event EventHandler listener; public event EventHandler BeginRequest; public event EventHandler EndRequest; public event EventHandler LogRequest; public event EventHandler PostAc Events; public event EventHandler listener; public event EventHandler PostLogRequest; public event EventHandler listener; public event EventHandler PostUpdate RequestCache; public event EventHandler caching; public event EventHandler ReleaseRequestState; public event EventHandler caching; public event EventHandler UpdateRequestCache; private void InitModules (); public void InitInternal (); public void ProcessRequest (HttpContext context);} HttpModule: Events in HttpApplication are executed in sequence. HttpContext is the process from the beginning of HttpApplication to the end of "stream ". Some column events are used to process HttpContext requests. Some events can be executed before they reach the real processing center (generally processed by the processing program) or later. For example, AuthenticateRequest is a verification request used to obtain user information; PostAcquireRequestState is used to obtain the Session, which can be obtained only after this event. Therefore, we can register different events at different times to better extend the HTTP application request processing. httpModule is not specified in the configuration file. Instead, an HttpModules folder is specified to traverse all cs files in the folder and create an IHttpModule through reflection, run its Init method private void InitModules () {HttpModuleCollection moduleCollection = new HttpModuleCollection (); if (Directory. exists ("Modules") {string [] modulesPath = Directory. getFiles ("Modules"); foreach (string item in modulesPath) {if (File. exists (item) {if (Path. GetExtension (item) = ". cs ") {string moduleName = Assembly. getEntryAssembly (). getName (). name + ". modules. "+ Path. getFileNameWithoutExtension (item); IHttpModule module = Assembly. getEntryAssembly (). createInstance (moduleName) as IHttpModule; moduleCollection. addModule (moduleName, module); module. init (this) ;}}}}in the IHttpModule, there is only one Init method, this method uses the HttpApplication type, you can register the Event Response Method of HttpApplication here: Public interface IHttpModule {void Init (HttpApplication context);} IHttpHandler: This is the same as our general processing program. We inherit this interface in a class to implement this ProcessRequest method. HttpHandler is the real processing center of Http requests and is created and executed in the event pipeline of HttpApplication. Public interface IHttpHandler {void ProcessRequest (HttpContext context);} That's all. Let's sort out the idea: When an http request arrives at the server, the server listens to the socket request, obtain the http request message. HttpContext encapsulates the http request. The ProcessRequest method of the HttpApplication object is used to process the request. Finally, the response packet is encapsulated and returned to the browser. Now, let's try it out: first put the Asp.. Net assembly is compiled into a dll file. Like in the previous article, create a WinForm application and introduce our MyWebApplication assembly. The listening client request can be changed like this. while (true) {Socket clientSocket = serverSocket. accept (); byte [] data = new byte [1024*1024]; int len = clientSocket. receive (data, 0, data. length, SocketFlags. none); if (len <= 0) {clientSocket. shutdown (SocketShutdown. both); clientSocket. close (); continue;} string strRequest = Encoding. UTF8.GetString (data, 0, len); HttpContext context = new HttpContext (strRequest); // create a context object if (Context. request. url. endsWith (". aspx ") | context. request. url. endsWith (". ashx ") {HttpApplication application = new HttpApplication (); application. processRequest (context); // create an Application and execute the PR method} else // if it is a static file, find its Path and read the byte into the output stream {string fileData = Path. combine (AppDomain. currentDomain. baseDirectory + context. request. url. trimStart ('/'). replace ('/', '\'); if (! File. exists (fileData) {context. response. write ("this path does not exist");} else {context. response. write (File. readAllBytes (fileData) ;}} clientSocket. send (context. response. responseHeader); clientSocket. send (context. response. responseBody); clientSocket. shutdown (SocketShutdown. both); clientSocket. close () ;}}, socket); then, we create a Modules folder for storing the extended HttpModule file. -- MyHttpModule creates a handler that inherits from IHttpHandler -- SimpleHandler public class TestHandler: IHttpHandler {public void ProcessRequest (HttpContext context) {string id = context. request. queryString ["id"]; string name = context. request. queryString ["name"]; string path = context. server. mapPath ("Test.html"); string html = File. readAllText (path); string replaceStr = string. format ("id: {0} <br/> name: {1}", id, name ); Html = html. Replace ("@ test", replaceStr); context. Response. Write (html); context. Response. Write ("<br/> HttpHandler execution is complete! <Br/> ") ;}} let's also test HttpModule Extension: public class MyModule: IHttpModule {public void Init (HttpApplication context) {context. beginRequest + = context_BeginRequest; context. endRequest + = context_EndRequest;} // void context_EndRequest (object sender, EventArgs e) {HttpApplication app = sender as HttpApplication; HttpContext context = app. context; context. response. write ("<br/> HttpModule --- EndRequest is executed <br/>");} // This is the first event void context_BeginRequest in HttpApplication (object sender, EventArgs e) {HttpApplication app = sender as HttpApplication; HttpContext context = app. context; context. response. write ("HttpModule --- BeginRequest executed <br/>") ;}} start our server access: http://127.0.0.1:9999/TestHandler.aspx?id=23&name=Test We use this. cs class as a dynamic request, followed by aspx or ashx. As you can see, our HttpModule also takes effect here: we prefer to execute the BeginRequest event registered in HttpModule and then output the execution results in HttpHandler, as well as get request parameters... HttpHandler execution completed! Finally, execute the EndRequest event registered in HttpModule.

Related Article

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.