且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-24 21:31:35

找到了解决方案:

我认为,由于创建了一个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.