asp.net 利用Web.config实现整站301永久重定向

1、在web.config加入配置

  <appSettings>
    <add key="WebDomain" value="mhzg.net"/>
    <add key="URL301Location" value="www.mhzg.net"/>
  </appSettings>

2、在当前解决方案下新建一个类库项目

3、新建一个cs,命名为:Domain301.cs

using System;
using System.Web;
using System.Configuration;
namespace Domain
{
    public class RedirectNewDomain : IHttpModule
    {
        public void Dispose()
        {
        }
        public void Init(HttpApplication context)
        {
            context.AuthorizeRequest += (new EventHandler(Process301));
        }
        public void Process301(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            HttpRequest request = app.Context.Request;
            string lRequestedPath = request.Url.DnsSafeHost.ToString();
            string strDomainURL = ConfigurationManager.AppSettings["WebDomain"].ToString();
            string strWebURL = ConfigurationManager.AppSettings["URL301Location"].ToString();
            if (lRequestedPath.IndexOf(strWebURL) == -1)
            {
                app.Response.StatusCode = 301;
                app.Response.AddHeader("Location", lRequestedPath.Replace(lRequestedPath, "http://" + strWebURL + request.RawUrl.ToString().Trim()));
                app.Response.End();
            }
        }
    }
}

4.在web.config里注册

<httpModules>
      <add name="Redirect301" type="RedirectNewDomain, Domain"  />
</httpModules>







郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。