1. Preface
This article is short mainly because of a piece of code that I want to generate. The function of this code can be called simple Http server or Http Request Interception. The function is to intercept Http requests and process them by yourself.
2: Code
Copy codeThe Code is as follows:
Public class HttpServer: IDisposable
{
Private HttpListener listener;
Public void Start ()
{
Listener = new HttpListener ();
Listener. Prefixes. Add ("http: // localhost /");
Listener. AuthenticationSchemes = AuthenticationSchemes. IntegratedWindowsAuthentication | AuthenticationSchemes. Anonymous;
Listener. Start ();
Listener. BeginGetContext (GetContext, null );
}
Private void GetContext (IAsyncResult ar)
{
HttpListenerRequest Request;
HttpListenerResponse Response;
Try
{
HttpListenerContext ctx = listener. EndGetContext (ar );
Request = ctx. Request;
Response = ctx. Response;
// Setup waiting for the next request
Listener. BeginGetContext (GetContext, null );
}
Catch (InvalidOperationException)
{
Return;
}
Catch (HttpListenerException)
{
Return;
}
Try
{
Var sw = new StreamWriter (Response. OutputStream );
Sw. Write (@ "Sw. Flush ();
}
Finally
{
Response. OutputStream. Flush ();
Response. Close ();
}
}
Public void Dispose ()
{
If (listener! = Null)
Listener. Stop ();
}
}
3: A Brief Explanation
The core of the Code is HttpListener, which listens to a port. When there is a request, BeginGetContext is handed over to the GetContext Method for asynchronous processing. The first internal implementation of this method is re-listening. Then perform your own processing.
What are the other functions of this code to be considered.