Introduction
I often map HTML extension to the ASP.NET DLL in order to use URL rewriter with .html extensions. In a recent project, we renamed all URLs to end with .html. This works great, but failed when we used FCK Editor. Static HTML files would not get served because we mapped the HTML extension to the .NET Framework. We can use .html extension with our rewriter but still want to use IIS behavior with static HTML files.
Analysis
I thought that this could be resolved with a simple HTTP handler. We would map URLs of static files in our rewriter to this handler that would read the static file and serve it, just as IIS would do.
Implementation
This is how I coded the class. Note that this may not be bullet proof. I only tested it once and I am sure that the logic behind IIS is more complicated that this. If you find errors or think of possible improvements, let me know.
Imports System.Web
Imports System.Web.Services
Public Class ISAPIDotNetHandler
Implements System.Web.IHttpHandler
Sub ProcessRequest(ByVal context As HttpContext) _
Implements IHttpHandler.ProcessRequest
context.Response.ContentType = "text/html"
Try
Dim uri As String = context.Request("fileUri")
If String.IsNullOrEmpty(uri) Then
Throw New ApplicationException("No fileUri")
End If
If Not uri.ToLower.EndsWith(".html") Then
Throw New ApplicationException("Extension not allowed")
End If
Dim fullPath As String = context.Server.MapPath(uri)
Dim stream As IO.StreamReader = _
FileIO.FileSystem.OpenTextFileReader(fullPath)
context.Response.Output.Write(stream.ReadToEnd)
stream.Close()
stream.Dispose()
stream = Nothing
Catch ex As Exception
context.Response.StatusCode = 404
Finally
context.Response.Flush()
context.Response.End()
End Try
End Sub
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
Conclusion
As you see, with our static files mapping to this handler using query string (e.g.: /ISAPIDotNetHandler.ashx?fileUri=index.html) you will have the same behavior as if you ask for the URL/index.html.
Finally, test this only in IIS with the HTML extension map to aspnet_isapi.dll. URL rewriting will work in Casini (Internal Web Server shipped with Visual Studio) but it's not the same as with IIS since EVERY request is handled by .NET.
Versions
Category: CodeProject
Published: 4/19/2009 11:25 PM