Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Http library in c#

Tags:

c#

http

I'm in the process of embedding a small web server into my program. It's relatively simple - only needs to serve up raw html files and javascript.

I have some async networking code I can use to get the basic plumbing. But are there any readily available libraries that can understand http?

I just need to be able to parse the http request to extract the path, query string, post variables and to be able to respond accordingly.

No need for SSL or cookies or authentication.

I tried a couple of web-server libraries but were not satisfied, mostly because they use worker threads that make interaction with the UI of the program annoying.

Ideally, I just want a library that would take some http request string\stream and give me back a structure or object.

like image 538
HS. Avatar asked Apr 20 '09 16:04

HS.


2 Answers

I think that HttpListener might do what you want.

EDIT: (added code sample just in case)

Here's a little code to show how you can use it (using async methods).

HttpListener _server = new HttpListener();

// add server prefix (this is just one sample)
_server.Prefixes.Add("http://*:8080");

// start listening
_server.Start();

// kick off the listening thread
_Server.BeginGetContext(new AsyncCallback(ContextCallback), null);

and then in ContextCallback(IAsyncResult result)

// get the next request
HttpListenerContext context = _server.EndGetContext(result);

// write this method to inspect the context object
// and do whatever logic you need
HandleListenerContext(context);

// is the server is still running, wait for the next request
if (_Server.IsListening)
{
    _server.BeginGetContext(new AsyncCallback(ServerThread), null);
}

Take a look at HttpListenerContext for details on what you have available to you, but the main one will probably be the Request property.

like image 109
Erich Mirabal Avatar answered Sep 18 '22 21:09

Erich Mirabal


Why don't you use the classes from the System.Net namespace? Especially HttpListener.

like image 36
Daniel Brückner Avatar answered Sep 20 '22 21:09

Daniel Brückner