gpt4 book ai didi

asp.net - Razor 引擎在 .Net Core 类库中找不到我的 View

转载 作者:行者123 更新时间:2023-12-02 14:15:12 27 4
gpt4 key购买 nike

我有我的类库,其中包含 ViewRenderService 类:

public interface IViewRenderService
{
Task<string> RenderToStringAsync(string viewName, object model);
}

public class ViewRenderService : IViewRenderService
{
private readonly IRazorViewEngine _razorViewEngine;
private readonly ITempDataProvider _tempDataProvider;
private readonly IServiceProvider _serviceProvider;

public ViewRenderService(IRazorViewEngine razorViewEngine,
ITempDataProvider tempDataProvider,
IServiceProvider serviceProvider)
{
_razorViewEngine = razorViewEngine;
_tempDataProvider = tempDataProvider;
_serviceProvider = serviceProvider;
}

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 = _razorViewEngine.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();
}
}

还有很多 View ,它们从路径开始:我的类库根/Views//共享/许多 View

问题是,IRazorViewEngine找不到我的 View ,我应该如何调用viewRenderService.RenderToStringAsync(?)来渲染~/Views/Shared例如/Myview.cshtml

最佳答案

我处理类库中 View 的方式是使 View 嵌入资源,即在我的 .csproj 文件中

<ItemGroup>
<EmbeddedResource Include="Views\**" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>

你需要这个包:

<PackageReference Include="Microsoft.Extensions.FileProviders.Embedded" Version="1.1.*" />

然后我的类库中有一个扩展方法,如下所示:

public static RazorViewEngineOptions AddCloudscribeSimpleContentBootstrap3Views(this RazorViewEngineOptions options)
{
options.FileProviders.Add(new EmbeddedFileProvider(
typeof(Bootstrap3).GetTypeInfo().Assembly,
"cloudscribe.SimpleContent.Web.Views.Bootstrap3"
));

return options;
}

然后在主应用程序的 Startup.cs 中,您必须选择使用扩展方法来包含这些 View ,如下所示:

services.AddMvc()
.AddRazorOptions(options =>
{
options.AddCloudscribeSimpleContentBootstrap3Views();
});

关于asp.net - Razor 引擎在 .Net Core 类库中找不到我的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44632224/

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