tags:

views:

595

answers:

2
+2  Q: 

Http library in c#

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.

+5  A: 

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.

Erich Mirabal
+2  A: 

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

Daniel Brückner
"This class is available only on computers running the Windows XP SP2 or Windows Server 2003 operating systems."
Ian Boyd