gpt4 book ai didi

c# - 如何实现RazorViewEngine FindView缓存

转载 作者:行者123 更新时间:2023-11-30 17:56:57 25 4
gpt4 key购买 nike

我正在继承 RazorViewEngine我正在尝试覆盖 FindView,但我对使用 ViewLocationCache 实现缓存的方式感到困惑。

谁能举个例子?

最佳答案

我终于明白了。这是我的整个实现:

public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
{
//Implement defualt exceptions
if(controllerContext == null)
throw new ArgumentNullException("The controllerContext parameter is null");
if(string.IsNullOrEmpty(viewName))
throw new ArgumentException("The viewName parameter is null or empty.");

//Check cache if specified
if(useCache && this.ViewLocationCache != null){
string cachedLocation = ViewLocationCache.GetViewLocation(controllerContext.HttpContext, generateCacheKey(controllerContext, viewName));
if (!string.IsNullOrEmpty(cachedLocation))
return new ViewEngineResult(CreateView(controllerContext, cachedLocation, masterName), this);
}

//Create arguments for location formatting
string trimmedViewName = string.Empty;
if (viewName.EndsWith(".cshtml"))
trimmedViewName = viewName.Remove(viewName.Length - 7);
else
trimmedViewName = viewName;
object[] args = new object[] { trimmedViewName, controllerContext.RouteData.GetRequiredString("controller"), controllerContext.RouteData.GetRequiredString("module") };

//Attempt to locate file
List<string> searchedLocations = new List<string>();
foreach(string location in ViewLocationFormats){
string formatedLocation = string.Format(location,args);
searchedLocations.Add(formatedLocation);
if (FileExists(controllerContext, formatedLocation))
{
//File has been found. Add to cache and return view
if(this.ViewLocationCache != null)
ViewLocationCache.InsertViewLocation(controllerContext.HttpContext, generateCacheKey(controllerContext, viewName), formatedLocation);

return new ViewEngineResult(CreateView(controllerContext, formatedLocation, masterName), this);
}
}

//Couldnt find view, return searched locations
return new ViewEngineResult(searchedLocations);
}
public string generateCacheKey(ControllerContext controllerContext, string viewName)
{
return string.Format("{0}|{1}", controllerContext.RouteData.GetRequiredString("module"), viewName);
}

关于c# - 如何实现RazorViewEngine FindView缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13675784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com