代码之家  ›  专栏  ›  技术社区  ›  olivierr91

找不到位于引用项目中的视图

  •  0
  • olivierr91  · 技术社区  · 8 年前

    我的解决方案包括两个项目:

    • 我的应用。休息
    • 我的应用。果心

    Core使用Razor模板生成电子邮件和报告。Rest只是一个WebAPI,它引用了内核。Rest有一个启动文件,Razor配置就是在这个文件中进行的。Core还将在未来被其他项目使用。

    问题是,我无法使视图引擎定位视图文件,即使我已将输出目录添加为razor的文件提供程序,并且模板已复制到输出目录。

    输出目录:

    MyApp.Code.dll
    MyApp.Rest.dll
    RazorTemplates
     -> Template1.cshtml
    

    创业。反恐精英

    services.AddMvc()
        .AddApplicationPart(typeof(MyApp.Core.RazorViewRenderer).GetTypeInfo().Assembly)
        .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
        .AddDataAnnotationsLocalization();
    
    services.Configure<RazorViewEngineOptions>(o => {
        o.ViewLocationFormats.Add("/RazorTemplates/{0}" + RazorViewEngine.ViewExtension);
        o.FileProviders.Add(new PhysicalFileProvider(AppContext.BaseDirectory));
    });
    

    RazorViewRenderer。反恐精英:

    public async Task<string> RenderAsync<TModel>(string name, TModel model) {
        var actionContext = GetDefaultActionContext();
        var viewEngineResult = _viewEngine.FindView(actionContext, "Template1", true);
    
        if (!viewEngineResult.Success) {
            throw new InvalidOperationException($"View '{name}' cannot be found."); //Craches here.
        }
    
        var view = viewEngineResult.View;
        using (var output = new StringWriter()) {
            var viewContext = new ViewContext(actionContext, view,
                new ViewDataDictionary<TModel>(
                    metadataProvider: new EmptyModelMetadataProvider(),
                    modelState: new ModelStateDictionary()) {
                    Model = model
                },
                new TempDataDictionary(
                    actionContext.HttpContext,
                    _tempDataProvider),
                output,
                new HtmlHelperOptions());
    
            await view.RenderAsync(viewContext);
            return output.ToString();
        }
    }
    

    注意:RazorLight不是一个选项。它不支持Html助手,也完全不支持本地化。

    2 回复  |  直到 8 年前
        1
  •  1
  •   olivierr91    8 年前

    使用GetView()而不是FindView()解决了我的问题。

    此外,本地化也被打破。我不得不使用自己的IViewLocalizer实现,因为在GitHub上查看微软的代码时,IViewLocalizer使用IHostingEnvironment中指定的程序集,该程序集设置为MyApp。用Rest代替MyApp。果心

        2
  •  0
  •   Ramesh Malviya    8 年前

    必须添加所有子文件夹路径

    o.ViewLocationFormats.Add("/Views/RazorTemplates/{0}.cshtml");