首先,新建301重定向过滤器函数RedirectFilter:
using System.Web.Mvc;
namespace Bosins.Web
{
public class RedirectFilter : IResultFilter
{
public void OnResultExecuting(ResultExecutingContext filterContext)
{
// 301重定向
var currentUrl = filterContext.HttpContext.Request.Url.ToString();
if (currentUrl.Contains("匹配关键字"))
{
string newUrl = "新要跳转的地址";
filterContext.HttpContext.Response.StatusCode = 301;
filterContext.HttpContext.Response.AppendHeader("Location", newUrl);
filterContext.HttpContext.Response.AppendHeader("Cache-Control", "no-cache");
//filterContext.Result = new RedirectResult(currentUrl, true);
}
}
public void OnResultExecuted(ResultExecutedContext filterContext)
{
// 在结果执行后不需要进行任何操作
}
}
}
然后,在Global的Application_Start()函数中,将新建的301重定向过滤器添加到全局过滤器:
GlobalFilters.Filters.Add(new RedirectFilter());
完成!