Implement your own ASP.NET host system

xiaoxiao2021-03-06  111

Implement your own ASP.NET host system Yangshan River 1. Host concept hosting is a very basic concept of .NET, all .NET application code to fully function to enter the hosted environment (CLR - Comm - Common Language Runtime), This environment is actually called the host (Host) to be prepared for the .NET code that will be started. At present, on the Windows system, there are 3 types of saved programs that are responsible for this heavy responsibility: 1. Shell (usually Explorer), provide startup .NET programs from the user desktop, create a process, start this process to establish CLR 2, browser The host, handles .NET code execution from the web download. 3. Server hosts (such as IIS Auxiliary Process ASPNET_WP.EXE) Usually, we developed ASP.NET programs run in an IIS environment (actually starting CLR by an ISAPI control), but actually ASP.NET program You can get rid of IIS to run in any hosted environment. This article discusses how the ASP.NET program starts in a custom environment, hoping to help us understand the progress of the ASP.NET, while making us developed ASP.NET can be executed in any .NET environment, no matter the server operation The system is still an ordinary desktop operating system. Second, the implementation of ASP.NET in the IIS host About the details of ASP.NET in IIS, many articles have made detailed authority, this article does not plan to give some references here: http://www.yesky. COM / SoftChannel / 72342380468043776/20030924 / 1731387.shtmlhttp: //chs.gotdotnet.com/quickstart/aspplus/doc/prockmodel.aspx These articles are generally analyzed: How to start, how will the ASP.NET application generate programs? Set, how to load, interact with the host. Third, constructing your own ASP.NET host program ASP.NET is the alternative technology of Microsoft ASP, so we focus on how to apply ASP.NET through web mode (obviously other ways), specific: we use .NET The platform's language is written in a console program, which launches an ASP.NET application environment to perform requests for ASPX. Specifically, you need to do the following: 1. Implement a web server to listen to all web requests, implement HTTP Web Hosting 2, start an application domain, create an ASP.NET ApplicationHost, create an ASP.NET application The domain, and the specific implementation class of HTTPWORKERREQUEST, which can process the ASPX request, compile the ASPX page, and the compiled managed code cache into the current application domain, then execute the code to get the execution result. It is recommended to carefully check the two categories of these two classes in the MSDN before continuing reading. System.Web.hosting.ApplicationHost class is used to create a separate application domain. Of course, it is not an ordinary application domain, but to establish an execution environment for ASP.NET, preparing the required space, data structure, etc.

There is only one static method Static Object CreateApplicationHost (Type Host // Specific user implementation class, that is, the ASP.NET application domain requires load class string virtualdir, // This application field executes directory in the entire Web, virtual directory String PhysicalDir / / Corresponding physical directory); where the Host parameter points to a specific class, since the class actually belongs to the contact class between the two application domains, grouping data between two application domains, so you must inherit Since MARSHALBYREFOBJECT to allow access to application domain boundaries in support applications (as for why, recommendations 3). It can be seen that we need to start two application domains (Web Server feature application domains and ASP.NET application domains), and these two (application) domains are referenced by flow objects in cross-(application) domain. To achieve, the results executed in the ASP.NET domain can be returned to the requester through the web server domain.

The web server-side web client code implementation of the ASP.NET can be expressed approximately the following picture: use system.web.hosting; using system.io; useing system.net; use system.net. Sockets; using system.threading; namespace myiis {class asphostserver {[stathread] static void main (string [] args) {// creates and launched server myserver myserver = new myserver ("/", "C: // inetpub // wwwroot // myWeb ");}} Class MyServer // Processing the HTTP protocol server class {Private aspdotNethost AspnetHost; //asp.net Host instance private tcplistener mytcp; // web listening socket Bool Bsvcrunning = True; // Service Whether running Indicates FileStream Fs; // Processes the common text of the HTTP request Requires public myserver (String Virtualdir, vstring realpath) {// Start Web listening service in the constructor try {MyTCP = New TCPListener (8001) Mytcp.start (); // Start listening at 8001 ports Console.WriteLine ("Service Start ..."); // Create an independent application domain to perform ASP.NET programs aspnetHost = (AspdotNethost) using the CreateApplicationHost method ApplicationHost.createApplicationHost (aspdotnetHost), Virtualdir, RealPath; Thread T = New THR ead (new ThreadStart (MainSvcThread)); t.Start (); // start the thread responsible for handling service requests each client's} catch (NullReferenceException) {Console.WriteLine ( "NullReferenceException throwed!");}} public void MainSvcThread ( ) //ASP.NET HOST's main service thread {INT S = 0; String strRequest; // Request information string strdir; // Request directory String strrequestFile; // Request file name String Strerr = "" // Error message string string string string strWebroot = rpath; // Apply root directory string strrehensfile = ""; // Disk path string string string string string string string string string struponse = ""; // Responding to the response buffer Strmsg = ""; // Format Response Information Byte [] BS; // Output byte Buffer While (BSVCRunning) {socket SCK = MyTCP.Acceptsocket ();

// Each request arrives if (Sck.Connected) {Console.Writeline ("Client {0} Connected!", Sck.RemoteEndPoint; byte [] BRECV = New Byte [1024]; // Buffer INT L = SCK .Receive (BRECV, BRECV.LENGTH, 0); String strbuf = encoding.default.getstring (brecv); // Convert into string for easy analysis S = strbuf.indexof ("http", 1); string httpver = strbuf .Substring (s, 8); // http / 1.1 strb.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); // acquire the URL IF (strDir == "/") {strdir = strWebroot;} else {Strdir = strdir.replace ("/", "//"); strRealdir = strWebroot strdir; "Client Request Dir: {0}", strRealdir); if (strrequestfile.length == 0) {Strrequestfile = "default.htm"; // Default document} int itotlabytes = 0; // Total byte strretsponse = ""; // output content strRealFile = strRealDir "//" strrequestFile; IF Strrealfile.endswith (". aspx")) // There is bug !! {string output = ""; // Note that the following statements have passed a ref type to the Host object processRequest method, // aspnetHost will ASP.NET's execution application domain executes a request to return to the current web server, which actually occurs in a domain call aspnetHost.ProcessRequest (StrRequestFile, Ref output); // Convert into byte stream BS =

System.Text.Encoding.default.getbytes (OUTPUT); itotlabytes = BS.LENGTH; // Call Sockets Return to WriteHeader (Httpver, "Text / Html", ITTLABYTES, "200 OK", Ref SCK; Flushbuf (BS, Ref SCK);} else {try {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, BS.LEngth))! = 0) {strresponse = strresponse encoding.default.getstring (BS, 0, RB); ITOTLABYTES = ITTLABYTES RB;} reader.close (); fs.close (); WriteHeader (httpver, "text / html", itotlabytes, "200 ok", ref SCK; Flushbuf (BS, Ref SCK);} catch System.io.filenotFoundException) {// Assumption No file, report 404 Writehead (Httpver, "Text / HTML", ITOTLABYTES, "404 OK", Ref SCK;}}} Sck.Close (); // http Request end}} // WriteHeader wants the client to send http headed public void writehead (String Ver, String Mime, Int Len, String Sta Tucode, 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 Customer Send Information Buffer Public Void Flushbuf (Byte [] BS, Ref Socket SCK {INT INUM = 0;

Try {if (Sck.Connected) {IF ((Inum = Sck.send (BS, BS.LENGTH, 0)) == - 1) {Console.WriteLine ("Flush Err: Send Data Err");} else { Console.writeline ("Send Bytes: {0}", Inum);}} else {console.writeline ("Client Diconnectioned!");}}} Catch (exception e) {Console.writeLine ("Error: {0}" , e);}}} // ASPDOTNETHost class instances need to cross two application domain, so the inherited from MarshalByRefObject class ASPDOTNETHost: MarshalByRefObject {public void ProcessRequest (string fileName, ref string output) {MemoryStream ms = new MemoryStream (); / / Memory flow, of course, for speed streamwriter sw = new streamwriter (ms); // output SW.AUTOFLUSH = true; // is set to Auto Refresh / First Construct a HTTPWorkRequest request class so that ASP.NET can analyze the request information, Passing an output stream object to return HTML stream HttpWorkerRequest worker = new simpleWorkerRequest (filename, ", sw); // dispatch a page, behind this StreamReader SR = New StreamReader (MS); // Preparing to read MS.Position = 0 from the memory stream; // Move pointer to head output = sr.readToEnd ();} }} Httpruntime.processRequest (Worker); What details are included? Based on: (SW object). This has a cross-(application) domain called by the current application domain of Web Server to our own ASP.NET application domain, which may also occur due to the first access, or the session event, or the session event. 2. ASP.NET's application domain detects if the requested ASPX file exists, does not exist, reports an error; if there is a code that exists in the code cache, if there is, and the ASP.NET detected You need to recompile, you will directly execute the code in the cache; if you do not exist or need to recompile, you need to read the ASPX file, compile it into a .NET code, deposit the cache. Some pages may have code and template separation into multiple files, even some resource files, which require read after compiling virtual machine code, and then execute in the hosted environment.

转载请注明原文地址:https://www.9cbs.com/read-102897.html

New Post(0)