您的位置:首页 > 编程语言 > ASP

asp.net web页面 实现301重定向

2017-05-03 16:44 459 查看
首先在web.config里面    httpModules 下 添加

<httpModules>

<add name="RedirectNewDomain" type="WZX.WebSite.Common.RedirectNewDomain, WZX.WebSite.Common" />

</httpModules>


接下来新建  RedirectNewDomain 类,继承接口  IHttpModule 

 

public class RedirectNewDomain : IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.AuthorizeRequest += (new EventHandler(Process301));
}
public void Process301(object sender, EventArgs e)
{
bool flag301 = ConvertHelper.ToType<bool>(SettingHelper.Settings["flag301"], false);  //读取配置文件中是否开启301
if (flag301)
{

HttpApplication app = (HttpApplication)sender;
HttpRequest request = app.Context.Request;
string AbsolutePath = request.Url.AbsolutePath;
if (string.IsNullOrEmpty(AbsolutePath) || AbsolutePath == "/")
app.Context.RewritePath("~/new/index.aspx");
else
{
//string AbsolutePath = "/new/aboutBrand";
if (!AbsolutePath.Contains(".aspx") && !AbsolutePath.Contains("/new/js/") && !AbsolutePath.Contains("/new/css/") && !AbsolutePath.Contains("/new/images/"))
{
//string strWebURL = request.Url.Host;
//string url = "http://" + strWebURL + GetPageUrl(AbsolutePath);
//app.Response.StatusCode = 301;
//app.Response.AddHeader("Location", url);
//app.Response.End();

app.Context.RewritePath("~" + GetPageUrl(AbsolutePath));
}
}
}

}

public string GetPageUrl(string AbsolutePath)
{
string PageUrl = AbsolutePath;

if (AbsolutePath.Contains("/introduction"))
{
PageUrl = "/new/aboutBrand.aspx";
}
//首页
else if (AbsolutePath.Contains("/index"))
{
PageUrl = "/new/index.aspx";
}
//新闻详情
else if (AbsolutePath.Contains("/new/newsDetail"))
{
PageUrl = "/new/newsDetail.aspx";
}
//新闻动态-欧罗来-eurol
else if (AbsolutePath.Contains("/news"))
{
if (AbsolutePath.Contains("/detail"))
{
Regex regex = new Regex(@"/news/detail_(?<productID>\d+)");
Match match = regex.Match(AbsolutePath);
if (match.Success)
{
string productID = match.Groups["productID"].Value;

PageUrl = regex.Replace(AbsolutePath, "/new/newsDetail.aspx?Id=" + productID);

}
else
{
PageUrl = "/new/news.aspx";
}
}
else
{
Regex regex = new Regex(@"/news_(?<NewType>\d+)");
Match match = regex.Match(AbsolutePath);
if (match.Success)
{
string NewType = match.Groups["NewType"].Value;
PageUrl = regex.Replace(AbsolutePath, "/new/news.aspx?NewType=" + NewType);
}
else
{
PageUrl = "/new/news.aspx";
}
}
}
//联系我们
else if (AbsolutePath.Contains("/contact"))
{
PageUrl = "/new/visitUs.aspx";
}
return PageUrl;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: