将视图呈现为核心 3.0 中的字符串:找不到与 ActionContext 关联的 IRouter

Rendering view to string in core 3.0: Could not find an IRouter associated with the ActionContext

我想要的:

在我的应用程序中,我想为我的电子邮件使用一个模板。不幸的是,我之前在另一个项目中使用的代码不再有效。

抛出的错误:

Could not find an IRouter associated with the ActionContext. 

If your application is using endpoint routing then you can get a IUrlHelperFactory with dependency injection 
and use it to create a UrlHelper, or use Microsoft.AspNetCore.Routing.LinkGenerator.'

我不知道如何解决这个问题,因为我找不到任何方法来注入 IUrlHelper。我不确定为什么需要它,因为它不在视图中。

字符串渲染方式:

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 = FindView(actionContext, viewName);

        if (viewResult == 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,
                    viewDictionary,
                    new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),
                    sw,
                    new HtmlHelperOptions());

        await viewResult.RenderAsync(viewContext); // Throws error <<<
        return sw.ToString();
    }
}

找到解决方案:

我想,由于创建一个 ActionContext 并为其提供一个空的 RouteData 对象会给我一个 IRouter 异常,下一个最佳解决方案是看看我是否可以只使用实际请求中的 HttpContext。

因此,通过依赖注入,我添加了 _httpContextAccessor 并使用了可用的 HttpContext 对象。

为了完整起见,我将分享最终实现:

将视图渲染到 HTML:

RenderToString(字符串, 对象);

var htmlBody = await Renderer.RenderToString($"/Views/Shared/confirm-email.cshtml", model);

服务:

public class ViewRenderService : IViewRenderService
{
    private readonly IRazorViewEngine _razorViewEngine;
    private readonly ITempDataProvider _tempDataProvider;
    private readonly IHttpContextAccessor _contextAccessor;

    public ViewRenderService(IRazorViewEngine razorViewEngine,
                             ITempDataProvider tempDataProvider,
                             IHttpContextAccessor contextAccessor)
    {
        _razorViewEngine = razorViewEngine;
        _tempDataProvider = tempDataProvider;
        _contextAccessor = contextAccessor;                                                                                            
    }

    public async Task<string> RenderToString(string viewName, object model)
    {
        var actionContext = new ActionContext(_contextAccessor.HttpContext, _contextAccessor.HttpContext.GetRouteData(), new ActionDescriptor());

        await using var sw = new StringWriter();
        var viewResult = FindView(actionContext, viewName);

        if (viewResult == 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,
            viewDictionary,
            new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),
            sw,
            new HtmlHelperOptions()
        );

        await viewResult.RenderAsync(viewContext);
        return sw.ToString();
    }

    private IView FindView(ActionContext actionContext, string viewName)
    {
        var getViewResult = _razorViewEngine.GetView(executingFilePath: null, viewPath: viewName, isMainPage: true);
        if (getViewResult.Success)
        {
            return getViewResult.View;
        }

        var findViewResult = _razorViewEngine.FindView(actionContext, viewName, isMainPage: true);
        if (findViewResult.Success)
        {
            return findViewResult.View;
        }

        var searchedLocations = getViewResult.SearchedLocations.Concat(findViewResult.SearchedLocations);
        var errorMessage = string.Join(
            Environment.NewLine,
            new[] { $"Unable to find view '{viewName}'. The following locations were searched:" }.Concat(searchedLocations));

        throw new InvalidOperationException(errorMessage);
    }
}

现在完美运行了。