Implement your own ASP. NET host system

Source: Internet
Author: User
Tags hosting web hosting net domain

1. Concept of host
Hosting is. net is a very basic concept, all. to fully utilize the net application code, you need to enter the managed environment (CLR -- Common Language Runtime), which is actually called the host to be started.. Net code. Currently, there are three types of stored programs on Windows:
1. Shell (usually Explorer) allows you to start the. NET program from the user's desktop, create a process, and start the process to create the CLR
2. the browser host (Internet Explorer) processes the. NET code downloaded from the web for execution.
3. server host (for example, iis's auxiliary process aspnet_wp.exe)
In general, we developed ASP. net program is running in the IIS environment (in fact, the CLR is started under the control of an ISAPI), but ASP.. net programs can run independently in any hosting environment. This article discusses ASP. net program in a custom environment, hope to help us understand ASP. net implementation principle, while enabling the ASP. net can be used in any.. NET environment, whether it is a server operating system or a common desktop operating system.

Ii. Execution Analysis of ASP. NET in the IIS HOST
Many articles have made detailed and authoritative analysis on the execution details of ASP. NET in IIS. This article does not describe it in detail. Here are some references:
These articles focus on the following details: How the host ring starts, how ASP. NET applications generate an assembly, how to load, and how to interact with the host.

3. construct your own ASP. NET Host Program
ASP. net is an alternative technology of Microsoft ASP, so we will focus on how to apply ASP through web. net (obviously there are other methods), specifically: we use.. NET platform language to compile a console program, which starts an ASP.. NET application environment to execute aspx requests. Specifically, you need to do the following:
1. Implement a Web server, listen to all Web requests, and implement HTTP web hosting
2. Start an application domain and create an ASP. net applicationhost to create an ASP. in addition, a specific implementation class of httpworkerrequest is also created, which can process aspx requests, compile the ASPX page, and cache the compiled managed code into the current application domain, then run the code to obtain the execution result. We recommend that you carefully review the references for these two classes in msdn before proceeding to the following sections.
The system. Web. Hosting. applicationhost class is used to create an independent application domain. Of course, it is not a common application domain, but an execution environment for ASP. NET to prepare the required space and data structure. There is only one static method static object createapplicationhost (
Type host // The specific user implementation class, which is the class to be loaded by the ASP. NET application domain.
String virtualdir, // The execution directory of this application domain in the entire web, virtual directory
String physicaldir // corresponding physical directory
The host parameter points to a specific class. Because the class actually belongs to the association class between two application domains and data is transferred in groups between the two application domains, it must inherit from marshalbyrefobject, to allow cross-application domain boundary access in supporting applications (for the reason, we recommend that you refer to 3 ).
We can see that we need to start two application domains (Web Server functional application domain and ASP.. NET application domain), and these two (Application) domains are implemented through cross-(Application) domain Stream object reference, so that in ASP.. Net domain execution results can be returned to the requester through the Web server domain.
Can be roughly expressed
Web server that executes ASP. NET




Web Client

Code Implementation Analysis:
Using system;
Using system. Web;
Using system. Web. Hosting;
Using system. IO;
Using system. net;
Using system. net. Sockets;
Using system. text;
Using system. Threading;

Namespace myiis
Class asphostserver
Static void main (string [] ARGs)
// Create and start the server
Myserver = new myserver ("/", "C: // inetpub // wwwroot // myweb ");

Class myserver // server class for processing HTTP protocol
Private aspdotnethost aspnethost; // ASP. NET host instance
Private tcplistener mytcp; // web listening socket
Bool bsvcrunning = true; // indicates whether the service is running.
Filestream FS; // common text requirements for processing HTTP requests

Public myserver (string virtualdir, vstring realpath)
{// Start the Web Listener service in the constructor
Mytcp = new tcplistener (8001 );
Mytcp. Start (); // start the listener on port 8001.
Console. writeline ("Service Startup ...");
// Create an independent application domain using the createapplicationhost method to execute ASP. NET programs
Aspnethost = (aspdotnethost) applicationhost. createapplicationhost
(Typeof (aspdotnethost), virtualdir, realpath );
Thread t = new thread (New threadstart (mainsvcthread ));
T. Start (); // The service thread starts to process requests from each client.
Catch (nullreferenceexception)
Console. writeline ("nullreferenceexception throwed! ");

Public void mainsvcthread () // main service thread of the Web server of ASP. NET host
Int S = 0;
String strrequest; // request information
String strdir; // requested directory
String strrequestfile; // request file name
String strerr = ""; // error message
String strrealdir; // actual directory
String strwebroot = rpath; // application root directory
String strrealfile = ""; // disk path of the file being requested
String strresponse = ""; // Response Buffer
String strmsg = ""; // format the response
Byte [] BS; // output byte Buffer

While (bsvcrunning)
Socket sck = mytcp. acceptsocket (); // the arrival of each request
If (sck. Connected)
Console. writeline ("client {0} connected! ", Sck. remoteendpoint );
Byte [] brecv = new byte [1024]; // buffer zone
Int L = sck. Receive (brecv, brecv. length, 0 );
String strbuf = encoding. Default. getstring (brecv); // convert the string to facilitate analysis
S = strbuf. indexof ("HTTP", 1 );
String httpver = strbuf. substring (S, 8); // such as HTTP/1.1
Strrequest = strbuf. substring (0, s-1 );
Strrequest. Replace ("//","/");
If (strrequest. indexof (".") <1 )&&(! Strrequest. endswith ("/")))
Strrequest + = "/";
S = strrequest. lastindexof ("/") + 1;
Strrequestfile = strrequest. substring (s); strdir = strrequest. substring (strrequest. indexof ("/"), strrequest. lastindexof ("/")-3); // obtain the access URL
If (strdir = "/")
Strrealdir = strwebroot;
Strdir = strdir. Replace ("/","//");
Strrealdir = strwebroot + strdir;
Console. writeline ("client request dir: {0}", strrealdir );
If (strrequestfile. Length = 0)
Strrequestfile = "default.htm"; // default document
Int itotlabytes = 0; // The total number of bytes to be output.
Strresponse = ""; // output content
Strrealfile = strrealdir + "//" + strrequestfile;
If (strrealfile. endswith (". aspx") // there is a bug !!
String output = "";
// Note that the following statements pass a ref-type parameter to the processrequest method of the Host object,
// Aspnethost executes a request from the ASP. Net execution application domain and returns the stream to the domain of the current web server.
Aspnethost. processrequest (strrequestfile, ref output); // convert to word throttling
BS = system. Text. encoding. Default. getbytes (output );
Itotlabytes = BS. length; // call the socket to return the execution result
Writeheader (httpver, "text/html", itotlabytes, "200 OK", ref sck );
Flushbuf (BS, ref sck );
FS = new filestream (strrealfile, filemode. Open, fileaccess. Read, fileshare. Read );
Binaryreader reader = new binaryreader (FS); // read
BS = new byte [fs. Length];
Int RB;
While (rb = reader. Read (BS, 0, BS. Length ))! = 0)
Strresponse = strresponse + encoding. Default. getstring (BS, 0, Rb );
Itotlabytes = itotlabytes + RB;
Reader. Close ();
FS. Close ();
Writeheader (httpver, "text/html", itotlabytes, "200 OK", ref sck );
Flushbuf (BS, ref sck );
Catch (system. Io. filenotfoundexception)
{// If no file is found, report 404 writeheader (httpver, "text/html", itotlabytes, "404 OK", ref sck );
Sck. Close (); // HTTP request ends

// Writeheader
Public void writeheader (string ver, string mime, int Len, string statucode, ref socket sck ){
String Buf = "";

If (mime. Length = 0)
Mime = "text/html ";

Buf = BUF + Ver + statucode + "/R/N ";
Buf = BUF + "server: myiis" + "/R/N ";
Buf = BUF + "Content-Type:" + mime + "/R/N ";
Buf = BUF + "Accept-rabges: bytes" + "/R/N ";
Buf = BUF + "Content-Length:" + Len + "/R/n/R/N ";
Byte [] BS = encoding. Default. getbytes (BUF );
Flushbuf (BS, ref sck );

// Flushbuf refresh the message buffer sent to the customer
Public void flushbuf (byte [] BS, ref socket sck)
Int inum = 0;
If (sck. Connected)
If (inum = sck. Send (BS, BS. length, 0) =-1)
Console. writeline ("Flush err: send data Err ");
Console. writeline ("Send Bytes: {0}", inum );
Console. writeline ("client diconnectioned! ");
Catch (exception E)
Console. writeline ("error: {0}", e );

// The aspdotnethost class instance must span two application domains, so it inherits from marshalbyrefobject
Class aspdotnethost: marshalbyrefobject
Public void processrequest (string filename, ref string output)
Memorystream MS = new memorystream (); // memory stream, of course for speed
Streamwriter Sw = new streamwriter (MS); // output
SW. autoflush = true; // set to automatic refresh/construct an httpworkrequest class for ASP. net can analyze and obtain request information, and input an output stream object for ASP.. net returns the HTML stream during execution.
Httpworkerrequest worker = new simpleworkerrequest (filename, "", SW); // schedule a page, which contains many details.
Httpruntime. processrequest (worker );
Streamreader sr = new streamreader (MS); // prepare to read from memory stream
Ms. Position = 0; // move the pointer to the header
Output = Sr. readtoend ();
Httpruntime. processrequest (worker); what details are included? In general:
1. First, the worker object is passed to ASP.. NET application domain, indicating which aspx file is requested, and what is the current directory. If the output content occurs during execution, it should be written to the SW object ). This occurs from the current application domain of Web server to the ASP created by ourselves. NET application domain Cross-(Application) domain call, may also be because of the first access, there will be a global event, or session event.
2. asp. the application domain of net checks whether the requested aspx file exists and does not exist. If yes, an error is returned. If yes, check whether the last compiled code exists in the Code cache. If ASP exists. net detects that the code in the cache does not need to be re-compiled. If the Code does not exist or expires, you need to re-compile the code, you need to read the aspx file and compile it.. Net code, which is stored in the cache. Some pages may have code and templates separated into multiple files, or even some resource files, which need to be read and compiled into. net virtual machine code, and then executed in the hosting environment.
3. Execute the code in the ASP. NET compilation code cache, and output data is output using the SW object.
Of course, according to different configurations, there are many details such as method calls/events.
How can I debug and run the above programs and observe the results?
Create a console type project, input and compile the above Code, and copy the program to the bin subdirectory that serves as the initial directory of the site application (such as C:/inetpub/wwwroot/myweb, then, create ASP.. NET application domain will not cause errors due to assembly loading failure. Create an asp.netproject in the directory, and upload the default.htm file and test. aspx, Add. and then start IE. in the address bar, enter http: // 8001/default.htm http: // 8001/test. aspx feels the execution process. You can even set breakpoints in a project to debug and observe the details. Try it by yourself. You must have something to gain!

Iv. Significance of Self-constructing an ASP. NET host
I spent half a day working on my own ASP. NET host. What does it mean to us?
First, ASP is clearly analyzed from the code level. net execution details, learn the execution details, in addition to ASP. net faults can be precisely located and eliminated, and can also help us write ASP. NET application to write more efficient and robust code.
Secondly, we can provide an idea to run our ASP. Net program on a low-configuration machine without IIS. The "original configuration" host IIS of ASP. NET needs to run on the Server OS. In the eyes of security experts, IIS is one of the sources of major risks. We can write many traditional programs using ASP. NET, but they are executed independently from IIS, for example, ASP. NET on Win98. Web server and ASP.. the rich management and control functions provided by the. NET platform make writing B/S programs closer to the traditional programming methods, which guarantees the efficiency of coding and execution.
In addition, for projects using ASP. NET, you can easily perform development, debugging, operation, maintenance, and installation. Even for a common desktop program, we can write these interfaces and codes in a way similar to creating web pages. Then, we can independently create a host environment similar to this example and load and execute some pages according to user interaction requests, the interface is displayed on the client through related components. You can use this to obtain the ASP. net real-time compilation function and the ASP. NET host hosting environment, a large number of freely available APIs for development, installation, and maintenance. After all, the hosting environment provides almost all the features you need.

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: 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.