Skip to content
Scott Offen edited this page Apr 12, 2014 · 33 revisions

#Welcome to the Grapevine Cookbook!# Create a new VisualStudio project, reference Grapevine and System.Net (for the HttpListener stuff), and start exploring Grapevine!

##Extending HttpResponder## The first thing you'll want to do is create a class that extends HttpResponder. In the examples throughout this cookbook (and in the SampleServer project), we use a class called RestServer.

using System.Net;
using Grapevine;

namespace SampleServer
{
    class RestServer : HttpResponder
    {
        [Responder(Method = HttpMethod.GET, PathInfo = @"^/foo/\d+$")]
        public void HandleFoo(HttpListenerContext context)
        {
            this.SendResponse(context, "FOO IS SUCCESS");
        }
    }
}

HttpResponder does not have any methods you are required to implement. However, methods with the Responder attribute are expected to provide a response. You can use the SendResponse helper method, illustrated above. For a little more control, use SendTextResponse.

[Responder(Method = HttpMethod.GET, PathInfo = @"^/foo/\D+$")]
public void HandleMoeFoo(HttpListenerContext context)
{
    context.Response.StatusDescription = "I'm a teapot";
    context.Response.ContentType = "text/plain";
    context.Response.StatusCode = 418;

    this.SendTextResponse(context, "Make your own coffee, foo!");
}

Responder has two properties: Method (enum Grapevine.HttpMethod) and PathInfo (a regular expression string to be matched). Both have default values; HttpMethod.GET and "/", respectively.

You can also apply multiple attributes to the same method, and it will respond to all matching scenarios, even if they use different HTTP methods!

        [Responder(Method = HttpMethod.GET, PathInfo = @"/foo/\d+")]
        [Responder(Method = HttpMethod.POST, PathInfo = @"/bar/\d+")]
        public void HandleFoo(HttpListenerContext context)
        {
            ...        
        }

Be aware that Grapevine will use the first method it finds that meets it's criteria, so if you intend to use catch-all or drop-through style methods, the order that they are in the class file will matter.

##Controlling Server Startup## The easiest way to start up a server is by using the zero argument constructor. This provides the following defaults:

  • host : localhost
  • port : 1234 (must be a STRING!)
  • threads : 5

You can change any of these values via the public properties before calling server.Start(), but attempting to change them while the server is running will result in a InvalidStateException being thrown.

var server = new RestServer();
server.Host = "127.0.0.1";
server.Port = "6543";
server.MaxThreads = 25;

server.Start();
// Attempting to change them now will throw an error!

You can also provide these values when you instantiate your server;

var server = new RestServer("127.0.0.1", "6543", 25);
// And you can still change them again before you start the server!

##Changing the Webroot## By default, any request that does not have a handler will next be treated like a request for a static file. The default location for files is the webroot subfolder in the same directory as the executable. If this directory doesn't exist, the server will attempt to create it.

You can change the webroot folder at any time - even while the server is running!

server.WebRoot = @"c:\path\to\new\webroot";

From that point on, all requests for files will be served out of the new folder. If he folder doesn't exist, the server will attempt to create it before changing the value of webroot.

##404 Not Found## If there is no Responder or static file that matches the request, a 404 error is automatically returned.

##Serving Known/Unknown Files## When serving up files, Grapevine will try to determine what type of file it is - both to read the file using the right kind of readers and so it can set the appropriate Content-type header.

To do this, Grapevine utilizes the content-type.json file. If you want your server to dish up files not on the list, add them like so:

{
	"Extension" : "PDF",
	"MIMEType" : "application/pdf",
	"IsText" : false
}

Any file extensions not found on this list will be treated as plain text (text/plain).

##Remote Server Shutdown## Any class that extends HttpResponder has the ability to cause the server to shutdown. I prefer to use the DELETE method and the /shutdown PathInfo for this, but you there is no requirement to do so.

[Responder(Method = HttpMethod.DELETE, PathInfo = @"^/shutdown$")]
public void RemoteShutDown(HttpListenerContext context)
{
    this.SendTextResponse(context, "Shutting down, Mr. Bond...");
    this._listening = false; // This shuts things down nicely
}

##Parsing JSON## If you're interested in passing around JSON data and don't know where to turn, I'd recommend using Json.NET.

##Contact Me## I'd love to hear from anyone using Grapevine, if for no other reason than to know someone else is finding this package useful. Email me, or, if you are having problems, open an issue.

Thanks for checking out Grapevine!

Clone this wiki locally