它不会一直发生,但是经过大量使用后,我的网站似乎变慢了很多,我唯一更改的代码就是更改重定向。
路由查找旧类别(不再使用)并将其替换为新类别。所以有人如何去 example.com/scary-shows/buffy 将被重定向到 example.com/television/buffy
我试图找出性能损失(如果它甚至发生在这里),以及我可以在哪里改进它。
全球.asax:
...
// custom constraint
routes.MapRoute("ArticlesCategories", "{category}/{page}",
new { controller = "Custom", action = "CategoryRedirect" },
new { isCategory = new CategoryRouteConstraint() });
//Article routes
routes.MapRoute("ArticlesRedirect", "Articles/Redirect",
new { controller = "_Articles", action = "Redirect" });
routes.MapRoute("ArticlesSubcategories", "articles/categories/{filter}/{section}",
new { controller = "_Articles", action = "Filter", filterBy = "categories", section = UrlParameter.Optional });
routes.MapRoute("ArticlesTags", "articles/tags/{filter}",
new { controller = "_Articles", action = "Filter", filterBy = "tags" });
...
约束:
public class CategoryRouteConstraint:IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values,
RouteDirection routeDirection)
{
string page = string.Format("{0}", values["page"]);
string urlCategory = string.Format("{0}", values["category"]);
if (GetCategoryDictionary().ContainsKey(urlCategory))
{
string topCategory = GetCategoryDictionary()[urlCategory];
values.Add("topCategory",topCategory);
return true;
}
return false;
}
private static List<Category> _categoryList = null;
private static object _lockObj = new object();
private static Dictionary<string, string> _dictionary = null;
private static Dictionary<string, string> GetCategoryDictionary()
{
if (_dictionary != null) return _dictionary;
lock (_lockObj)
{
//check again...
if (_dictionary != null) return _dictionary;
var dictionary = new Dictionary<string, string>
{
{"my-old-example-category", "example"},
{"blogs", "Blog"},
{"doctor-notes", "Blog"},
{"action-movies", "movies"},
{"reality-tv", "television"},
{"scary-shows", "televsion"},
... this goes on for about 100 more categories ...
};
_dictionary = dictionary;
return dictionary;
}
}
}
控制器:
[OutputCache(Duration = 10800)]
public class CustomController : Controller
{
public ActionResult CategoryRedirect()
{
string topCategory = string.Format("{0}", RouteData.Values["topCategory"]);
string page = string.Format("{0}",RouteData.Values["page"]);
return RedirectPermanent(string.Format("/{0}/{1}", topCategory, page));
}
}