remove 'WWW' in ASP.NET MVC 1.0

2019-03-22 06:30发布

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

4条回答
放荡不羁爱自由
2楼-- · 2019-03-22 07:06

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

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

On IIS: Virtual Directory http://img138.imageshack.us/img138/4213/virtualdirectories.png

On Apache:

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

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

查看更多
Root(大扎)
3楼-- · 2019-03-22 07:14

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.

查看更多
疯言疯语
4楼-- · 2019-03-22 07:19

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
查看更多
来,给爷笑一个
5楼-- · 2019-03-22 07:24

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 Remove WWW

查看更多
登录 后发表回答