我在MVC之外使用Razor。我想将视图呈现为字符串。这是我的方法:
public async Task<string> RenderToStringAsync(string viewName, object model)
{
var httpContext = new DefaultHttpContext { RequestServices = _serviceProvider };
var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
using (var sw = new StringWriter())
{
var viewResult = _viewEngine.FindView(actionContext, viewName, false);
if (viewResult.View == null)
{
throw new ArgumentNullException($"{viewName} does not match any available view");
}
var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
{
Model = model
};
var viewContext = new ViewContext(
actionContext,
viewResult.View,
viewDictionary,
new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),
sw,
new HtmlHelperOptions()
);
await viewResult.View.RenderAsync(viewContext);
return sw.ToString();
}
}
我创建了Views文件夹并粘贴了几个视图。所有文件都有复制到输出目录 - 始终复制。但我接下来要到这里了
var viewResult = _viewEngine.FindView(actionContext, viewName, false);
viewResult具有属性Success,该属性始终为false,并且还具有值为“/Views/Shared/Email.cshtml”和“/Views//Email.cshtml”的属性SearchedLocations。有什么想法吗?
答案 0 :(得分:1)
默认视图位置为/Views/{1}/{0}.cshtml
和/Views/Shared/{0}.cshtml
可能控制器不存在(并且razor找不到控制器),所以在你的情况下它是/Views//Email.cshtml
。
您可以通过添加新的视图位置扩展器来添加自定义位置:
public class ViewLocationExpander : IViewLocationExpander
{
public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
{
var locationWithoutController = "/Views/{0}.cshtml";
return viewLocations.Union(new[] { locationWithoutController });
}
public void PopulateValues(ViewLocationExpanderContext context)
{
}
}
在Startup.cs中注册扩展器:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddRazorOptions(options =>
{
options.ViewLocationExpanders.Add(new ViewLocationExpander());
});
}