WinForm disconnects IIS from carrying Aspx requests

Source: Internet
Author: User
I. Proposal of requirements
My application needs to access a webservice. The data of webservcie is read from the socket and changes in real time. When the demand changes, if there is no ready-made data on the server, I have to simulate the data myself,
Create a website in IIS, build your own webservcie, and then add data. I just thought, without using IIS, you can directly use an application to provide the webservcie method. I initially wanted to use WCF, but after google for half a day, I didn't use the method for generating webservcie using wcf, or I didn't have enough rp.
2. Solutions
Finally, we found the solution. To use the winform program to host the IIS service, we established the winform program and listened to tcplistener. In this way, you can use an application to process the access through a browser.
The following is a reference method:
Http://www.microsoft.com/china/MSDN/library/WebServices/WebServices/ServiceStation.mspx? Mfr = true
Http://msdn.microsoft.com/zh-cn/magazine/cc163879 (en-us). aspx # fig5
Iii. Implementation
Download the source code and run the program.
The following is an online copy. I put it in a dll. Why? The reason is described below. Using System;
Using System. Collections. Generic;
Using System. Text;
Using System. IO;
Using System. Web;
Using System. Web. Hosting;

Namespace MyasmxHost
{
// The ASPDOTNETHost class instance must span two application domains, so it inherits from MarshalByRefObject
Public 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 ();
}
}
}

 

As a result, I started to run the program, but when I call ASPDOTNETHost, I always throw an exception and "failed to load part of MyasmxHost ". This problem has plagued me for a long time. google continues, and Niu Ren's answer is: MyasmxHost must be deployed in GAC. This is why I put ASPDOTNETHost in a dll.

1. Private deployment and global deployment of the application.

Private deployment: the dl required for your own application is under the application directory. Global Deployment: deploy dll or exe to GAC.

2. Strongly-named assembly:

 

 

Use sn.exe-I mycompany. keys

 

Put mycompany. keys in the dll and add a line [assembly: AssemblyKeyFile ("myasmxhost. keys")] In AssemblyInfo. cs.

3. Deploy it to gac. Use gacutil.exe-I *. dll to deploy to GAC

 

@ Echo off

: Set the location of gacutil.exe

Set gacuw.gacutil.exe

: Execute the deployment of gac
Start % gacu %-I MyasmxHost. dll
 

 

 

In this case, the exception is fixed. Everything is OK. Check the processing method of the server.

Server myserver

 

Public MyServer (string virtualDir, string realPath, int port)
{// Start the web Listener service in the constructor
Try
{

// Add TcpListerner to a fixed port
Mytcp = new TcpListener (port );
Mytcp. Start ();


// Create an independent application domain using the CreateApplicationHost method to execute ASP. NET programs
ASPnetHost = (ASPDOTNETHost) ApplicationHost. CreateApplicationHost
(Typeof (ASPDOTNETHost), virtualDir, realPath );
T = new Thread (new ThreadStart (MainSvcThread ));
T. Start ();
}
Catch (NullReferenceException)
{
Debug. Print ("NullReferenceException throwed! ");
}
}

 

(1) Add the header layer listener on the fixed port,

(2) create an independent application domain using the CreateApplicationHost method to execute ASP. NET programs

What needs to be done in the main thread is to get what is received and then send it out.

 

 

 

 

 

 

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 = @ "d: \ test"; // actual directory
String strWebRoot = @ "d: \ test"; // 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
Try
{
If (sck. Connected)
{
Debug. Print ("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;
}
Else
{
StrDir = strDir. Replace ("/","\\");
StrRealDir = strWebRoot + strDir;
}
Debug. Print ("Client request dir: {0}", strRealDir );
If (strRequestFile. Length = 0)
{
StrRequestFile = "default.html"; // default document
}
Int iTotlaBytes = 0; // The total number of bytes to be output.
StrResponse = ""; // output content
StrRealFile = strRealDir + "\" + strRequestFile;
// Process WebMonitorSvr. asmx? Situation of wsdl
If (strRealFile. IndexOf ("WebMonitorSvr. asmx? Wsdl ")! =-1)
{
StrRealFile = @ "D: \ test \ WebMonitorSvr. asmx ";
}
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 );
}
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, 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 );
Debug. Print ("Error 404 ");
}
}
}
}
Catch (System. Exception ex)
{
Debug. Print (ex. Message );
}
Finally
{
Sck. Close (); // Http request ends
}
}
}

Here, I set d: \ test as a virtual directory, and a default.html file is stored in it.

Main program diagram:

 

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.