如何让 razor 从模板服务中的另一个程序集中查找视图

Swa*_*odo 5 c# asp.net-mvc-areas razor .net-core asp.net-core-2.1

我正在尝试从另一个项目加载剃刀视图。我已经经历了几个不同的兔子洞,但到目前为止我还没有找到一种方法来完成这项工作。然而,根据我的研究,似乎有两种主要方法可以实现这一目标。

一种选择是使用嵌入式资源,然后将嵌入式文件提供程序连接到 razor 中。我可能是错的,但我认为这是 .net core 2.1 之前的方法。我的理解是,在 2.1 Razor 视图中,Razor 视图是在构建时编译的。将其设置为嵌入将保存实际文件,这对于旧的运行时编译很有用。

// Add the embedded file provider to be used with razor view templates
var viewAssembly = typeof(CoreStartup).GetTypeInfo().Assembly;
var fileProvider = new EmbeddedFileProvider(viewAssembly);
services.Configure<RazorViewEngineOptions>(o => o.FileProviders.Add(fileProvider));
services.AddTransient<ITemplateService, TemplateService>();
Run Code Online (Sandbox Code Playgroud)

另一种方法是将视图放入区域文件夹中。我什至找到了一个示例项目,它表明您完全可以做到这一点!但是,我一直无法找到获得相同结果的方法。

作为参考,这里是我尝试用来查找和渲染剃刀视图的服务。我需要从中获取 html 输出以帮助创建 html 电子邮件模板。

namespace TestApp.Services
{
    using System;
    using System.IO;
    using System.Threading.Tasks;

    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.Abstractions;
    using Microsoft.AspNetCore.Mvc.ModelBinding;
    using Microsoft.AspNetCore.Mvc.Razor;
    using Microsoft.AspNetCore.Mvc.Rendering;
    using Microsoft.AspNetCore.Mvc.ViewFeatures;
    using Microsoft.AspNetCore.Routing;
    using Microsoft.Extensions.Options;

    using Serilog;

    public class TemplateService : ITemplateService
    {
        private readonly IServiceProvider _serviceProvider;
        private readonly ITempDataProvider _tempDataProvider;
        private readonly IRazorViewEngine _viewEngine;

        public TemplateService(
            IServiceProvider serviceProvider,
            ITempDataProvider tempDataProvider,
            IRazorViewEngine viewEngine)
        {
            this._serviceProvider = serviceProvider;
            this._tempDataProvider = tempDataProvider;
            this._viewEngine = viewEngine;
        }

        public async Task<string> RenderTemplateAsync<TViewModel>(string viewPath, TViewModel viewModel)
        {
            var httpContext = new DefaultHttpContext
                                  {
                                      RequestServices = this._serviceProvider
                                  };

            return await RenderTemplateAsync(httpContext, viewPath, viewModel);
        }

        public async Task<string> RenderTemplateAsync<TViewModel>(HttpContext httpContext, string viewPath, TViewModel viewModel)
        {
            var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());

            var viewResult = this._viewEngine.FindView(actionContext, viewPath, false);
            if (!viewResult.Success)
            {
                Log.Error("Failed to render template {@viewPath} because it was not found.", viewPath);
                throw new FileNotFoundException($"Failed to render template {viewPath} because it was not found.");
            }

            var viewDictionary = new ViewDataDictionary<TViewModel>(new EmptyModelMetadataProvider(), new ModelStateDictionary());
            var tempDataDictionary = new TempDataDictionary(httpContext, this._tempDataProvider);

            using (var outputWriter = new StringWriter())
            {
                try
                {
                    var viewContext = new ViewContext(
                        actionContext, 
                        viewResult.View, 
                        viewDictionary,
                        tempDataDictionary, 
                        outputWriter, 
                        new HtmlHelperOptions());
                    viewContext.ViewData.Model = viewModel;

                    await viewResult.View.RenderAsync(viewContext);
                }
                catch (Exception ex)
                {
                    Log.Error(ex, "Failed to render template due to a razor engine failure");
                    throw;
                }

                return outputWriter.ToString().Replace("\r\n", string.Empty);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我这样调用服务。我已经尝试了路线中我能想到的所有可能的字符串,以尝试使其正常工作。问题是我不确定用于查找区域视图的确切格式。所以我不确定是路线错误还是连接不正确。

var body = await _templateService.RenderTemplateAsync(HttpContext, "Common/EmailDetails", emailModel);
Run Code Online (Sandbox Code Playgroud)

现在我正在尝试获取 EmailDetails.cshtml 共享视图。

/Areas
    /Common
        /Views
            /Shared
                -EmailDetails.cshtml
Run Code Online (Sandbox Code Playgroud)

小智 2

请检查这一点这仅适用于在应用程序目录中搜索视图:

public class MyViewLocationExpander : IViewLocationExpander
{

    public void PopulateValues(ViewLocationExpanderContext context)
    {

    }

    public virtual IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
    {
        return viewLocations.Select(f => f.Replace("/Views/", "/Areas/Common/Views/")); 
    }

}
Run Code Online (Sandbox Code Playgroud)

在启动类中:

services.Configure<RazorViewEngineOptions>(options =>
        {                
            options.ViewLocationExpanders.Add( new MyViewLocationExpander());                
        });
Run Code Online (Sandbox Code Playgroud)

如果您需要从应用程序“外部”加载视图,请检查:https: //www.mikesdotnetting.com/article/301/loading-asp-net-core-mvc-views-from-a-database-or-other -地点