remove 'WWW' in ASP.NET MVC 1.0

前端 未结 4 1287
被撕碎了的回忆
被撕碎了的回忆 2021-02-11 04:14

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

4条回答
  •  梦谈多话
    2021-02-11 04:30

    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
    

提交回复
热议问题