在核心3.0中将视图渲染为字符串:找不到与ActionContext关联的IRouter [英] Rendering view to string in core 3.0: Could not find an IRouter associated with the ActionContext

查看:80
本文介绍了在核心3.0中将视图渲染为字符串:找不到与ActionContext关联的IRouter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要的东西:

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

In my application, I want to use a template for my e-mails. Unfortunately code I used before in another project doesn't work anymore.

引发的错误:

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 的方法.我不确定为什么甚至需要这样做,因为无论如何视图中都没有.

I have no clue how to fix this because I can't find any way to inject the IUrlHelper. I'm unsure as to why this is even needed since it's not there in the view anyway.

字符串呈现方法:

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.

I figured that since creating an ActionContext and providing it with an empty RouteData object was giving me an IRouter exception, the next best solution was to see if I could just use the HttpContext from the actual request.

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

So through dependency injection, I added the _httpContextAccessor and used the available HttpContext object.

出于完整性考虑,我将分享最终实现:

For completeness sake I shall share the final implementation:

要将视图呈现为HTML:

RenderToString(string,object);

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);
    }
}

现在它可以正常工作了.

Now it works perfectly.

这篇关于在核心3.0中将视图渲染为字符串:找不到与ActionContext关联的IRouter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆