如何在ASP.NET 4.0中进行301重定向? [英] How to 301 redirect in ASP.NET 4.0?

查看:111
本文介绍了如何在ASP.NET 4.0中进行301重定向?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为网站实施URL重定向,而不是逐页进行.我想在global.asax文件中执行此操作.下面是我定义的代码.

I am trying to implement URL redirect for the website rather than doing it page by page. I want to do it in the global.asax file. Below is the code i have defined.

我想以 http://website.net 作为我的主要网址&如果有人键入 http://www.website.net ,则希望具有永久的URL重定向.

I want to have http://website.net as my main url & want to have a permanent URL redirect if someone types in http://www.website.net.

很遗憾,它不适用于实时网站.任何人都可以指出代码中的问题.该代码不会产生任何错误.

Unfortunately it is not working for the live website. Can anyone point out the problem in the code. The code doesn't generate any error.

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中执行上述操作-仅执行一次.您应该与每个请求挂钩.试试这个:

Main problem: Your're doing the above stuff in Application_Start - which is only executed once. You should hook up with each request. Try this:

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中进行配置:

An even better approach would be to use URL rewriting, which can be configured from within Web.Config:

Microsoft重写模块-强制网址上的www或从网址中删除www

这篇关于如何在ASP.NET 4.0中进行301重定向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆