Implementation Code for asp.net to intercept Http requests

Source: Internet
Author: User

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.

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.