Just answered this on separate thread, but i'll re-post
I opted to do this at the app level, instead of IIS. Here's a quick action filter I wrote to do this.. Simply add the class somewhere in your project, and then you can add [RequiresWwww] to a single action or an entire controller.
public class RequiresWww : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpRequestBase req = filterContext.HttpContext.Request;
HttpResponseBase res = filterContext.HttpContext.Response;
//IsLocal and IsLoopback i'm not too sure on the differences here, but I have both to eliminate local dev conditions.
if (!req.IsLocal && !req.Url.Host.StartsWith("www") && !req.Url.IsLoopback)
{
var builder = new UriBuilder(req.Url)
{
Host = "www." + req.Url.Host
};
res.Redirect(builder.Uri.ToString());
}
base.OnActionExecuting(filterContext);
}
}
Then
[RequiresWwww]
public ActionResult AGreatAction()
{
...
}
or
[RequiresWwww]
public class HomeController : BaseAppController
{
..
..
}
Hope that helps someone. Cheers!