1. Overview
The purpose of this article is to provide an HTTP service through C# code. Under normal circumstances, if we need to provide HTTP services to the outside world, the conventional practice is to implement it through. Sometimes our application or Windows service needs to provide some simple HTTP services to the outside world and can implement it by itself, thereby avoiding the deployment of IIS to increase system complexity. It must be emphasized here that it is some simple applications. If the application is more complicated and involves path parsing, HTML parsing, etc., it is more reliable to implement it in WEB.
It is actually a bit inappropriate to put HTTP, UDP and TCP in the same series, because UDP and TCP belong to the transport layer protocol, and HTTP belong to the application layer protocol. I hope readers will have a clear understanding first.
2. Provide services
First start the HHTP service:
if (!) { ("The server operating system does not support the establishment of Http Server, and a higher version of the operating system is required!"); return; } HttpListener httpListener = new HttpListener(); try { ("Starting Http service"); int port = 9000; ($"http://*:{port}/"); (); ("Http service started successfully."); } catch (Exception ex) { ($"start upHttpA service exception:{}"); return; }
Perform monitoring:
while (true) { ("Start listening..."); HttpListenerContext context = (); HttpListenerRequest request = ; string Method = (); ($"Received a request,URL:{ } Method:{Method}"); Response(context, "hello"); }
The code loops to listen, and the GetContext method will cause blockage. When a browser request is received, the server will immediately return "Hello".
The Response method is implemented as follows:
private static void Response(HttpListenerContext context, string responseTxt) { HttpListenerResponse response = ; = "html"; = Encoding.UTF8; using (Stream output = ) { byte[] buffer2 = Encoding.(responseTxt); (buffer2, 0, ); } }
Now open the browser and enter the address http://localhosthost:9000/ to see if you can see the results. (If you need to access through other machines, the machine must open the corresponding port of the firewall.)
Note: The program needs to be run in the administrator model to provide services.
Specific methods: Add new application list file to the project: modify the configuration information as follows:
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"> <security> <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> <requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> </requestedPrivileges> </security> </trustInfo>
3. Response
By obtaining the protocol type, different processing methods will be adopted for the GET and POST methods.
By obtaining the URL path and parsing it, the parameter values that can be entered by the user.
if (Method == "GET") { ($"Get:RawURL:{ }"); if (("/version")) { Response(context, "Simple Http Server Ver:0.11"); continue; } else { string username = ["username"]; string pwd = ["pwd"]; Response(context, $"Welcome:{username}"); continue; } }
The above code, if you enter: http://localhost:9000?username=hahaha
Output: Welcome:hahaha
Under the POST method, you can still obtain the parameters entered by the user through the URL, but the data transmitted through the Body needs to be read through other methods.
if (Method == "POST") { ($"POST:RawURL:{ }"); string content = GetPostInput(request); ($"Content:{ content}"); Response(context, "\"{'Result':'Success','Message':'Hello'}\""); continue; }
The GetPostInput method is implemented as follows:
private static string GetPostInput(HttpListenerRequest request) { Stream s = ; int count = 0; byte[] buffer = new byte[1024]; StringBuilder builder = new StringBuilder(); while ((count = (buffer, 0, 1024)) > 0) { (Encoding.(buffer, 0, count)); } (); (); (); return (); }
For convenience, it is best to use the json format for input and output data.
4. Debugging
Debugging can be done via Chrome or Postman.
Portal:
The introduction to C# network programming series includes three articles:
(one)UDP for C# Network Programming
(two)Introduction to C# Network Programming TCP
(three)Introduction to C# Network Programming HTTP
The above is the detailed content of the implementation example of c# providing an HTTP service. For more information about c# providing http service, please follow my other related articles!