将视图渲染为字符串在服务器上不起作用

时间:2019-03-01 14:20:47

标签: c# asp.net-mvc razor asp.net-core .net-core

我正在研究一种将视图转换为PDF的方法。我终于使它工作了,但是当我将其发布到测试服务器时,它行不通了吗?它只是给了我这个错误:

  

InvalidOperationException:找不到包'Microsoft.NETCore.App'的编译库位置

我发现尝试将视图转换为字符串时失败。

这是article,我在其中找到了用于将视图转换为字符串的服务

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.GetView(viewName, 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();
        }
    }
}

我尝试过的事情

  • 将MvcRazorCompileOnPublish设置为false
  • 在测试服务器上安装dotnet core SDK

1 个答案:

答案 0 :(得分:0)

我尝试将MvcRazorCompileOnPublish设置为false,然后工作了。.我之前尝试过此方法,但后来却不起作用,也许我键入了错误或将其放在错误的地方或其他地方:/

将其代码放入{projectname} .csproj文件中:

<MvcRazorExcludeRefAssembliesFromPublish>false</MvcRazorExcludeRefAssembliesFromPublish>
  <PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramework>

    <!--ADD THIS LINE-->
    <MvcRazorExcludeRefAssembliesFromPublish>false</MvcRazorExcludeRefAssembliesFromPublish>

    <TypeScriptToolsVersion>3.1</TypeScriptToolsVersion>
  </PropertyGroup>