Saturday, March 27, 2010

Writing Your Own HttpHandler in F# - Starting the Solution

So my friend, Ryan Riley, was talking to me the other day about building an HttpHandler using F#, but he had come across a problem... how to debug the handler using Visual Studio. Knowing how much it would irritate me not to be able to debug my F# web-related work, I set out to figure out how to get this kind of project started. I'm going to make this whole thing as simple as humanly possible. And when I say simple... I mean absurdly simple...

1. Create a new MVC web application.
2. Delete everything out of the project other than the web.config.
3. Remove all the references (all of them... I told you this would be absurdly simple...)
4. Now, add an F# class library project to the solution. Call it "FunctionalWeb.Framework".
5. Delete the .fsx file. (or if you feel strongly about it, don't.)
6. Add a reference in the F# class library to System.Web.
7. Rename Module1.fs to HttpHandler.fs.
8. Paste the following code within HttpHandler.fs file, and replace anything that's already there:

namespace FunctionalWeb.Framework

open System.Web;

type HttpHandler() =
interface IHttpHandler with
member this.ProcessRequest(context:HttpContext) =
context.Response.Write("Hello from a simple F# Http Handler!")
member this.IsReusable with get() = true

9. Add a reference to FunctionalWeb.Framework in your web project.
10. Replace the content of the web.config file with the following:

<?xml version="1.0"?>
<compilation debug="true" targetFramework="4.0">
<add verb="*" path="*" validate="false" type="FunctionalWeb.Framework.HttpHandler, FunctionalWeb.Framework"/>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true"/>
<remove name="FunctionalHandler"/>
<add name="FunctionalHandler" preCondition="integratedMode" verb="*" path="*" type="FunctionalWeb.Framework.HttpHandler, FunctionalWeb.Framework"/>

Your solution should look something like this (You may or may not have the nested files below the web.config):

11. Press F5. If all goes well, you should see something like this:

As long as you allowed Visual Studio to modify the web.config in order to allow debugging, you should be able to put a breakpoint in your F# HttpHandler file, and have Visual Studio hit the breakpoint.

Congrats! You've just gotten started building your own HttpHandler with F#.