简体   繁体   中英

remove 'WWW' in ASP.NET MVC 1.0

I am attempting to force the domain name to not use the 'www'. I want to redirect the user if attempted. I have seen very little on an MVC solution. Is there anyway to harness the routing built into MVC, or what the best solutions is.

Thanks

Implemented as an ActionFilter as that is MVC-like, and more explicit.

public class RemoveWwwFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var req = filterContext.HttpContext.Request;
        var res = filterContext.HttpContext.Response;


        var host = req.Uri.Host.ToLower();
        if (host.StartsWith("www.")) {
            var builder = new UriBuilder(req.Url) {
                Host = host.Substring(4);
            };
            res.Redirect(builder.Uri.ToString());
        }
        base.OnActionExecuting(filterContext);
    }
}

Apply the ActionFilter to your controllers, or your base controller class if you have one.

For an introduction to Action Filters, see Understanding Action Filters on MSDN.

[RemoveWwwFilterAttribute]
public class MyBaseController : Controller

Although I believe John Gietzen's answer is the most elegant solution, I was unable to implement do to a shared hosting environment. Determined to find a non-application driven solution I found this blog post which shows a good alternative method for IIS7. Thankfully DiscountASP.NET's has the URL Rewrite module available through the IIS Manager tool.

Following this blog post on creating a rewrite rule any URL with www in the domain will do a permanent 301 redirect to the non-www site. All while preserving the full paths.

Thanks for everyone's input.

This is more generic configuration as you can write it once in the URL Rewrite of the root IIS (not specific to a certain application pool) and it will automatically be applied to ALL your IIS websites without any dependency on your domain name.

IIS删除WWW

If you have control over the server, you should set up a virtual directory that accepts requests for "www.example.com" and permanently redirects (301) them to "example.com"

While this may be possible in ASP.NET MVC, it is not ASP's job to do this sort of redirecting.

On IIS: 虚拟目录

On Apache:

<VirtualHost *:80>
    ServerName www.example.com
    Redirect permanent / http://example.com/
</VirtualHost>

Both the IIS and the Apache settings will preserve the URL stem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM