首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将视图呈现为核心3.0中的字符串:无法找到与ActionContext关联的ActionContext

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

Stack Overflow用户
提问于 2019-12-12 09:57:03
回答 1查看 6.6K关注 0票数 15

我想要的:

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

引发的错误:

代码语言:javascript
复制
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的任何方法。我不知道为什么这是必要的,因为它不是在那里的意见反正。

字符串呈现方法:

代码语言:javascript
复制
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();
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-12-15 14:36:02

找到了一个解决方案:

我认为,由于创建一个ActionContext并为它提供一个空的RouteData对象给了我一个IRouter异常,所以下一个最好的解决方案就是看看我是否可以使用实际请求中的HttpContext。

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

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

将视图呈现给

RenderToString(string,object);

代码语言:javascript
复制
var htmlBody = await Renderer.RenderToString($"/Views/Shared/confirm-email.cshtml", model);

服务:

代码语言:javascript
复制
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);
    }
}

现在它工作得很好。

票数 28
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59301912

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档