我正在尝试为网站实现URL重定向,而不是逐页进行。我想在global.asax文件中执行此操作。以下是我定义的代码。
我希望将http://website.net作为我的主要网址,如果有人在http://www.website.net中输入,我希望有一个永久的URL重定向。
不幸的是,它不适用于实时网站。任何人都可以指出代码中的问题。代码不会产生任何错误。
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
if (HttpContext.Current.Request.Url.ToString().ToLower().Contains("http://website.net"))
{
HttpContext.Current.Response.Status = "301 Moved Permanently";
HttpContext.Current.Response.AddHeader("Location", Request.Url.ToString().ToLower().Replace("http://website.net", "http://www.website.net"));
}
}
主要问题:你在Application_Start
做了上述事情 - 只执行一次。你应该与每个请求联系起来。试试这个:
void Application_BeginRequest(object sender, EventArgs e)
{
// Code that runs on every request
if (HttpContext.Current.Request.Url.ToString().ToLower().Contains("http://website.net"))
{
HttpContext.Current.Response.Status = "301 Moved Permanently";
HttpContext.Current.Response.AddHeader("Location", Request.Url.ToString().ToLower().Replace("http://website.net", "http://www.website.net"));
}
}
更好的方法是使用URL重写,可以在Web.Config
中配置:
Microsoft rewriting module - Force www on url Or remove www from url
如果使用IIS 7或更高版本,最简单的解决方案是使用web.config中的httpRedirect元素。
<httpRedirect enabled="true" exactDestination="true" httpResponseStatus="Permanent">
<add wildcard="/MyOldAspFile.aspx" destination="/MyNewFile.aspx" />
<add wildcard="/MyOldHtmlFile.html" destination="/MyNewFile.aspx" />
</httpRedirect>
此方法非常强大,例如,如果您更改了域但页面相同,则只需添加:
<system.webServer>
<httpRedirect enabled="true" childOnly="true" destination="http://www.mynewdomain.com/" />
</system.webServer>
我在这里写了一篇小文章:ASP.NET 301 permanent redirects: the best solution
.NET版本4实际上具有改进的单页面实现功能 - redirectpermanent。
Response.RedirectPermanent(NEW_URL);
基于以前的正确和有用的答案,这里有几个具体的例子。假设您要删除旧页面(就像我一样),有几个选项。
选项1:修改Global.asax
void Application_BeginRequest(object sender, EventArgs e)
{
// Add permanent redirection for retired pages
if (Request.Url.LocalPath.ToLower().StartsWith("/[OLD PAGE NAME]"))
{
Response.RedirectPermanent("/[NEW PAGE NAME]", false);
}
}
选项2:修改web.config
<system.webServer>
<httpRedirect enabled="true" httpResponseStatus="Permanent">
<add wildcard="/[OLD PAGE NAME]" destination="/[NEW PAGE NAME]" />
</httpRedirect>
</system.webServer>
如果你不知道什么是应用程序域名,请使用类似的东西
protected void Application_BeginRequest(object sender, EventArgs e)
{
if(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority).Contains("localhost"))return;
var leftPartOfUrl = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority).ToLower();
if (leftPartOfUrl.StartsWith("http") && leftPartOfUrl.Split('.').Length == 1)
{
var fullUrl = HttpContext.Current.Request.Url.ToString();
HttpContext.Current.Response.Status = "301 Moved Permanently";
HttpContext.Current.Response.StatusCode = 301;
HttpContext.Current.Response.AddHeader("Location", fullUrl.Insert(fullUrl.IndexOf("://", StringComparison.Ordinal) + 3, "www."));
HttpContext.Current.Response.End();
}
}