Deploy ASP.NET MVC on IIS 6, solve 404, compression and performance problems

There are several problems with ASP.NET MVC application when
deployed on IIS 6.0:

Problem 1: Visiting your website’s homepage gives 404 when
hosted on a domain

You have done the wildcard mapping, mapped .mvc extention to
ASP.NET ISAPI handler, written the route mapping for Default.aspx
or default.aspx (lowercase), but still when you visit your homepage
after deployment, you get:

"/wp-content/images/A712A04B61778DF139F4C2DD69BDBC28.png">
"border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;"
height="273" alt="image" src=
"/wp-content/images/5118D90CBDE98BE508E0D53333AFF7F8.png"
width="430" border="0">

You will find people banging their heads on the wall here:

Solution is to capture hits going to “/” and then rewrite it to
Default.aspx:

"/wp-content/images/C95DEA54829B10281435D9BF44F76FE5.png">
"border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;"
height="61" alt="image" src=
"/wp-content/images/EA8AE2BA47E5D0E1FDA274A710591B87.png"
width="600" border="0">

You can apply this approach to any URL that ASP.NET MVC is not
handling for you and it should handle. Just see the URL reported on
the 404 error page and then rewrite it to a proper URL.

Problem 2: IIS 6 compression is no longer working after
wildcard mapping

When you enable wildcard mapping, IIS 6 compression no longer
works for extensionless URL because IIS 6 does not see any
extension which is defined in IIS Metabase. You can learn about IIS
6 compression feature and how to configure it properly from
href=
"http://msmvps.com/blogs/omar/archive/2006/08/10/iis-6-compression-quickest-and-effective-way-to-do-it-for-asp-net-compression.aspx">
my earlier post
.

Solution is to use an HttpModule to do the compression for
dynamic requests.

Problem 3: ASP.NET ISAPI does not cache Static Files

When ASP.NET’s DefaultHttpHandler serves static files, it
does not cache the files in-memory or in ASP.NET cache. As a
result, every hit to static file results in a File read. Below is
the decompiled code in DefaultHttpHandler when it handles a
static file. As you see here, it makes a file read on every hit and
it only set the expiration to one day in future. Moreover, it
generates ETag for each file based on file’s modified date.
For best caching efficiency, we need to get rid of that
ETag, produce an expiry date on far future (like 30 days),
and produce Cache-Control header which offers better control
over caching.

"/wp-content/images/4721B2CF92DBFBBA4E7086B12C8197AD.png">
image "/wp-content/images/9271445990B567740D050C138F4FB988.png"
width="600" border="0">

So, we need to write a custom static file handler that will
cache small files like images, Javascripts, CSS, HTML and so on in
ASP.NET cache and serve the files directly from cache instead of
hitting the disk. Here are the steps:

  • Install an HttpModule that installs a Compression Stream
    on Response.Filter so that anything written on Response gets
    compressed. This serves dynamic requests.
  • Replace ASP.NET’s DefaultHttpHandler that listens on *.*
    for static files.
  • Write our own Http Handler that will deliver compressed
    response for static resources like Javascript, CSS, and HTML.

"/wp-content/images/D42E82988AF0CF5D4D1C342C694208DD.png">
image "/wp-content/images/C6D0D77EB1254D157BADE35ED76A155C.png"
width="600" border="0">

Here’s the mapping in ASP.NET’s web.config for the
DefaultHttpHandler. You will have to replace this with your
own handler in order to serve static files compressed and
cached.

Solution 1: An Http Module to compress dynamic requests

First, you need to serve compressed responses that are served by
the MvcHandler or ASP.NET’s default Page Handler. The
following HttpCompressionModule hooks on the
Response.Filter and installs a GZipStream or
DeflateStream on it so that whatever is written on the
Response stream, it gets compressed.

"/wp-content/images/5A364F7A608461B5B8337A1ABBDF605F.png">
"border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;"
height="393" alt="image" src=
"/wp-content/images/4F293F36930FB0513D83CF2425A580F0.png"
width="596" border="0">

These are formalities for a regular HttpModule. The real
hook is installed as below:

"/wp-content/images/305F154307864AA5255D2EB350008B8E.png">
"border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;"
height="436" alt="image" src=
"/wp-content/images/290D581DA143EA7D043B8F344E4A58FB.png"
width="593" border="0">

Here you see we ignore requests that are handled by ASP.NET’s
DefaultHttpHandler and our own StaticFileHandler that
you will see in next section. After that, it checks whether the
request allows content to be compressed. Accept-Encoding
header contains “gzip” or “deflate” or both when browser supports
compressed content. So, when browser supports compressed content, a
Response Filter is installed to compress the output.

Solution 2: An Http Module to compress and cache static file
requests

Here’s how the handler works:

  • Hooks on *.* so that all unhandled requests get served by the
    handler
  • Handles some specific files like js, css, html, graphics files.
    Anything else, it lets ASP.NET transmit it
  • The extensions it handles itself, it caches the file content so
    that subsequent requests are served from cache
  • It allows compression of some specific extensions like js, css,
    html. It does not compress graphics files or any other
    extension.

Let’s start with the handler code:

"/wp-content/images/87144BE4DE96484BD415E174CC5012E6.png">
image "/wp-content/images/6B4FC8634A8C65AD9EB2752242CE9C69.png"
width="600" border="0">

Here you will find the extensions the handler handles and the
extensions it compresses. You should only put files that are text
files in the COMPRESS_FILE_TYPES.

Now start handling each request from
BeginProcessRequest.

"/wp-content/images/884B9B30FC99000A903AFE2F78E7F180.png">
image "/wp-content/images/8CA5E34E186C0CCBCFBFBF9C9C50723D.png"
width="598" border="0">

Here you decide the compression mode based on
Accept-Encoding header. If browser does not support
compression, do not perform any compression. Then check if the file
being requested falls in one of the extensions that we support. If
not, let ASP.NET handle it. You will see soon how.

"/wp-content/images/E8EF32ABC4491B195D488390DB9BF76D.png">
image "/wp-content/images/F3928FCBA4A7896E8ECAA789DC6FE787.png"
width="599" border="0">

Calculate the cache key based on the compression mode and the
physical path of the file. This ensures that no matter what the URL
requested, we have one cache entry for one physical file. Physical
file path won’t be different for the same file. Compression mode is
used in the cache key because we need to store different copy of
the file’s content in ASP.NET cache based on Compression Mode. So,
there will be one uncompressed version, a gzip compressed version
and a deflate compressed version.

Next check if the file exits. If not, throw HTTP 404. Then
create a memory stream that will hold the bytes for the file or the
compressed content. Then read the file and write in the memory
stream either directly or via a GZip or Deflate stream. Then cache
the bytes in the memory stream and deliver to response. You will
see the ReadFileData and CacheAndDeliver functions
soon.

"/wp-content/images/CC595F7526F59BCDC4E3B22AB579C36A.png">
image "/wp-content/images/342AD78F4F0621CFE1999363649D1E47.png"
width="600" border="0">

This function delivers content directly from ASP.NET cache. The
code is simple, read from cache and write to the response.

When the content is not available in cache, read the file bytes
and store in a memory stream either as it is or compressed based on
what compression mode you decided before:

"/wp-content/images/CD1A3C7B79920C2854D21E9B5B10BC3E.png">
image "/wp-content/images/7D044E7672BB13CCC56616C05082E586.png"
width="598" border="0">

Here bytes are read in chunk in order to avoid large amount of
memory allocation. You could read the whole file in one shot and
store in a byte array same as the size of the file length. But I
wanted to save memory allocation. Do a performance test to figure
out if reading in 8K chunk is not the best approach for you.

Now you have the bytes to write to the response. Next step is to
cache it and then deliver it.

"/wp-content/images/2D1E29BAF9CDE6BC5F9607F829BF1A08.png">
image "/wp-content/images/B87123305578439633A66F38EFBC28B8.png"
width="600" border="0">

Now the two functions that you have seen several times and have
been wondering what they do. Here they are:

"/wp-content/images/311FCB77394D5073F9776931C899F289.png">
image "/wp-content/images/0A658E51A16F5D2B1481BA7F5A589CD4.png"
width="599" border="0">

WriteResponse has no tricks, but
ProduceResponseHeader has much wisdom in it. First it turns
off response buffering so that ASP.NET does not store the written
bytes in any internal buffer. This saves some memory allocation.
Then it produces proper cache headers to cache the file in browser
and proxy for 30 days, ensures proxy revalidate the file after the
expiry date and also produces the Last-Modified date from
the file’s last write time in UTC.

How to use it

Get the HttpCompressionModule and
StaticFileHandler from:

"http://code.msdn.microsoft.com/fastmvc">http://code.msdn.microsoft.com/fastmvc

Then install them in web.config. First you install the
StaticFileHandler by removing the existing mapping for
path=”*” and then you install the HttpCompressionModule.

"/wp-content/images/2A358E64B6CC18B2EE145D96E6C2248F.png">
image "/wp-content/images/56C954F48B51E91B00E4CB1D64998BD3.png"
width="602" border="0">

That’s it! Enjoy a faster and more responsive ASP.NET MVC
website deployed on IIS 6.0.

Share this post : href=
"http://del.icio.us/post?url=http://msmvps.com/blogs/omar/archive/2008/06/30/deploy-asp-net-mvc-on-iis-6-solve-404-compression-and-performance-problems.aspx&;title=Deploy%20ASP.NET%20MVC%20on%20IIS%206,%20solve%20404,%20compression%20and%20performance%20problems"
target="_blank"> "http://blogs.msdn.com/blogfiles/rahulso/WindowsLiveWriter/IconsfordifferentSocialBookmarkingSites_B387/deliciou4.png"
border="0" alt="">del.icio.us
"http://digg.com/submit?phase=2&url=http://msmvps.com/blogs/omar/archive/2008/06/30/deploy-asp-net-mvc-on-iis-6-solve-404-compression-and-performance-problems.aspx&title=Deploy%20ASP.NET%20MVC%20on%20IIS%206,%20solve%20404,%20compression%20and%20performance%20problems"
target="_blank"> "http://blogs.msdn.com/blogfiles/rahulso/WindowsLiveWriter/IconsfordifferentSocialBookmarkingSites_B387/digg14.png"
border="0" alt="">digg
href=
"http://www.dotnetkicks.com/kick/?url=http://msmvps.com/blogs/omar/archive/2008/06/30/deploy-asp-net-mvc-on-iis-6-solve-404-compression-and-performance-problems.aspx&title=Deploy%20ASP.NET%20MVC%20on%20IIS%206,%20solve%20404,%20compression%20and%20performance%20problems"
target="_blank"> "http://blogs.msdn.com/blogfiles/rahulso/WindowsLiveWriter/IconsfordifferentSocialBookmarkingSites_B387/CropperCapture154.jpg"
border="0" alt="">dotnetkicks
"http://www.furl.net/store?s=f&to=0&u=http://msmvps.com/blogs/omar/archive/2008/06/30/deploy-asp-net-mvc-on-iis-6-solve-404-compression-and-performance-problems.aspx&ti=Deploy%20ASP.NET%20MVC%20on%20IIS%206,%20solve%20404,%20compression%20and%20performance%20problems"
target="_blank"> "http://blogs.msdn.com/blogfiles/rahulso/WindowsLiveWriter/IconsfordifferentSocialBookmarkingSites_B387/furl4.png"
border="0" alt="">furl
"https://favorites.live.com/quickadd.aspx?marklet=1&mkt=en-us&url=http://msmvps.com/blogs/omar/archive/2008/06/30/deploy-asp-net-mvc-on-iis-6-solve-404-compression-and-performance-problems.aspx&title=Deploy%20ASP.NET%20MVC%20on%20IIS%206,%20solve%20404,%20compression%20and%20performance%20problems"
target="_blank"> "http://blogs.msdn.com/blogfiles/rahulso/WindowsLiveWriter/IconsfordifferentSocialBookmarkingSites_B387/live4.png"
border="0" alt="">live
href=
"http://reddit.com/submit?url=http://msmvps.com/blogs/omar/archive/2008/06/30/deploy-asp-net-mvc-on-iis-6-solve-404-compression-and-performance-problems.aspx&title=Deploy%20ASP.NET%20MVC%20on%20IIS%206,%20solve%20404,%20compression%20and%20performance%20problems"
target="_blank"> "http://blogs.msdn.com/blogfiles/rahulso/WindowsLiveWriter/IconsfordifferentSocialBookmarkingSites_B387/reddit4.png"
border="0" alt="">reddit
"http://www.spurl.net/spurl.php?v=3&url=http://msmvps.com/blogs/omar/archive/2008/06/30/deploy-asp-net-mvc-on-iis-6-solve-404-compression-and-performance-problems.aspx&title=Deploy%20ASP.NET%20MVC%20on%20IIS%206,%20solve%20404,%20compression%20and%20performance%20problems"
target="_blank"> "http://blogs.msdn.com/blogfiles/rahulso/WindowsLiveWriter/IconsfordifferentSocialBookmarkingSites_B387/spurl8.png"
border="0" alt="">spurl
href=
"http://technorati.com/faves/?add=http://msmvps.com/blogs/omar/archive/2008/06/30/deploy-asp-net-mvc-on-iis-6-solve-404-compression-and-performance-problems.aspx&title=Deploy%20ASP.NET%20MVC%20on%20IIS%206,%20solve%20404,%20compression%20and%20performance%20problems"
target="_blank"> "http://blogs.msdn.com/blogfiles/rahulso/WindowsLiveWriter/IconsfordifferentSocialBookmarkingSites_B387/technora4.png"
border="0" alt="">technorati
href="http://myweb.yahoo.com/myresults/bookmarklet?u=http://msmvps.com/blogs/omar/archive/2008/06/30/deploy-asp-net-mvc-on-iis-6-solve-404-compression-and-performance-problems.aspx&t=Deploy%20ASP.NET%20MVC%20on%20IIS%206,%20solve%20404,%20compression%20and%20performance%20problems"
target="_blank"> "http://blogs.msdn.com/blogfiles/rahulso/WindowsLiveWriter/IconsfordifferentSocialBookmarkingSites_B387/yahoo9.png"
border="0" alt="">yahoo

21 Comments

  1. Hi Mehfuz,

    ActionFilter is a great way to selectively enable compression on some requests. My solution turns on compression for all requests. This way you don't need to include the filter attribute on all action methods.

  2. Hi Omar, as Mehfuz said I see a number of benifits of Action Filters over HttpModules, but before that just want to correct that You can apply the action filter on the Controller which in turn applies to all the action/public methods, it is not required to decorate method.

    1. I do not have to stick with a Fixed Cache Duration.

    2. Unable to exclude or need to have some kind of rule engine to exclude it from caching.

    3. One of the main reason of MVC becoming so poplular is TDD, with HTTPModules it is harder and sometime impossible to fit in TDD.

  3. Hi Kazi,

    I believe there's a confusion here. I haven't done caching for dynamic requests. My module is only for enabling compression site wide which does not have Action/Controller specific requirement.

  4. Hi Omar

    > Mapping wildcard extension to ASP.NET introduces the following problems…

    I don't think this is always true. If you avoid interfering with the request, then DefaultHttpHandler leaves the request unhandled, which means IIS comes back in and serves the file natively (and then you'll get all the expiration headers etc.). The problems you describe only apply when DefaultHttpHandler serves the request through StaticFileHandler.

    For details of how it chooses what to do, see sticklebackplastic.com/…/The+continuing+saga+of+StaticFileHandler++meet+DefaultHttpHandler.aspx

    Thanks for writing this blog post though; it has lots of nice ideas.

  5. Hi Steve,

    Thanks for the pointer. As I use a Response Filter to compress dynamic page output, so in my case, the DefaultHttpHandler calls StaticFielHandler to handle it. So, IIS 6 does not handle the file. This is why I made my custom Static File handler.

  6. Doesn't applying url format like

    “{controller}/{action}/{id}.aspx”

    solve such issues?

    I am still very new to asp.net mvc. And is using this type of url format. This solution will work in shared hosts also.

    Nirandas

  7. Hi Omar,

    Great job!

    One small detail, I think there is a mistake on the method you use for “non-handled” extensions:

    I removed the compressiontype parameter of the TransmitFileUsingHttpResponse in the lines below.

    private void TransmitFileUsingHttpResponse(HttpRequest request, HttpResponse response,

    string physicalFilePath, FileInfo file)

    {

    if (file.Exists)

    {

    // We don't cache/compress such file types. Must be some binary file that's better

    // to let IIS handle

    this.ProduceResponseHeader(response, Convert.ToInt32(file.Length), ResponseCompressionType.None,

    physicalFilePath, file.LastWriteTimeUtc);

    response.TransmitFile(physicalFilePath);

    Debug.WriteLine(“TransmitFile: ” + request.FilePath);

    }

    else

    {

    throw new HttpException((int)HttpStatusCode.NotFound, request.FilePath + ” Not Found”);

    }

    }

    Kind Regards!

  8. Sir,

    I am not using the MVC approach. After deploying the site on the server and implementing everything what you discussed in your earlier article, The “Resource not found” error is thrown. what should i do??

    Regards

    Prabhjot

  9. How I can get it with IIS7? It's doesn't work properly. Please, wrote strings in web.config I must change.

  10. Hi Zabir,

    Given we don't want to compress image files, why don't you simply remove “.png”, “.jpeg”, “.jpg”, “.gif” & “.bmp” extensions from FILE_TYPES so that they get bypassed and handled and cached by IIS?

  11. Hi Omar,

    Wonderful tutorial here. Just a doubt: Does it work with all versions of ASP.NET mvc? I have a site developed around the preview 2, so would this work on it?

  12. Hi,

    I tried the solution. On my development server it works beautifully.

    On the production server the compression works for .aspx and .asmx but not for .js and .css.

    I am assuming that the StaticFileHandler is not used at all by IIS7.

    Any ideas?

    Sparhawk

  13. You can turn on static file compression on IIS 7. I saw there was some config to change on IIS. Forgot.

  14. Hi, what I am seeing is that compression is working for my static files but caching is not when I have wildcard mapping. If I disable wildcard mapping then everything works.

    I tried your approach and it doesnt work for me, I get a bunch of bytes rendered on the html page (I think maybe its being double compressed) Do I need to turn off compression somewhere on IIS to do this?

    If I remove the compression module the page gets served but with lots of errors.

    Any ideas/suggestions why I am seeing slightly different behavior? Is it possible MS patched something since then that changes this a bit?

  15. I am getting the following error after deploying my site(IIS).

    I think problem is with connetionstring. PLEASE HELP..

    ERROR ::

    Server Error in '/Fed' Application.

    Login failed for user 'VOLLERASPNET'.

    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.Data.SqlClient.SqlException: Login failed for user 'VOLLERASPNET'.

    Source Error:

    An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>