2016-09-29 79 views
2

我有一个Emailer类,我通过依赖注入来发送电子邮件,这些电子邮件通过电子邮件获取视图的内容。该过程中,我有伟大的工程,除非该视图包含对基础URL助手的电话,如使用像这样的标签:在ASP.NET Core中渲染包含URL字符串的Razor视图

<a asp-controller="Project" asp-action="List">Open</a> 

这里是我使用的渲染视图成一个字符串代码:

private string renderViewAsString<TModel>(string folder, string viewName, TModel model) 
{ 
    var httpContext = new DefaultHttpContext { RequestServices = _serviceProvider }; 
    var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor()); 
    var viewEngineResult = _viewEngine.FindView(actionContext, folder + "/" + viewName, false); 
    var view = viewEngineResult.View; 

    var viewData = new ViewDataDictionary<TModel>(new EmptyModelMetadataProvider(), new ModelStateDictionary()); 
    viewData.Model = model; 

    var tempData = new TempDataDictionary(httpContext, _tempDataProvider); 

    using (var output = new StringWriter()) 
    { 
    var viewContext = new ViewContext(actionContext, view, viewData, tempData, output, new HtmlHelperOptions());   
    var task = view.RenderAsync(viewContext); 
    task.Wait(); 

    return output.ToString(); 
    } 
} 

_serviceProvider是IServiceProvider类型,而_viewEngine是IRazorViewEngine类型,它们都在构造函数中注入。

如果它引用它在task.Wait()生产线生产此异常的URL帮手:

Index was out of range. Must be non-negative and less than the size of the collection. 
Parameter name: index 

以此为调用堆栈:

at System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) 
at System.Collections.Generic.List`1.get_Item(Int32 index) 
at Microsoft.AspNetCore.Mvc.Routing.UrlHelper.get_Router() 
at Microsoft.AspNetCore.Mvc.Routing.UrlHelper.GetVirtualPathData(String routeName, RouteValueDictionary values) 
at Microsoft.AspNetCore.Mvc.Routing.UrlHelper.Action(UrlActionContext actionContext) 
at Microsoft.AspNetCore.Mvc.UrlHelperExtensions.Action(IUrlHelper helper, String action, String controller, Object values, String protocol, String host, String fragment) 
at Microsoft.AspNetCore.Mvc.ViewFeatures.DefaultHtmlGenerator.GenerateActionLink(ViewContext viewContext, String linkText, String actionName, String controllerName, String protocol, String hostname, String fragment, Object routeValues, Object htmlAttributes) 
at Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper.Process(TagHelperContext context, TagHelperOutput output) 
at Microsoft.AspNetCore.Razor.TagHelpers.TagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output) 
at Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.<RunAsync>d__0.MoveNext() 

如何解决这个问题而不必诉诸硬编码A元素或电子邮件内容?

回答

8

我能得到它的工作。调用堆栈提到没有找到一个路由器,所以它提供它的问题:

首先我说这是在构造函数中的参数DI对象:

IHttpContextAccessor accessor 

这在构造函数中:

_context = accessor.HttpContext; 

然后,我改变了功能,以这样的:

private string renderViewAsString<TModel>(string folder, string viewName, TModel model) 
{ 
    var actionContext = new ActionContext(_context, new RouteData(), new ActionDescriptor()); 
    var viewEngineResult = _viewEngine.FindView(actionContext, folder + "/" + viewName, false); 
    var view = viewEngineResult.View; 

    var viewData = new ViewDataDictionary<TModel>(new EmptyModelMetadataProvider(), new ModelStateDictionary()); 
    viewData.Model = model; 

    var tempData = new TempDataDictionary(_context, _tempDataProvider); 

    using (var output = new StringWriter()) 
    { 
    var viewContext = new ViewContext(actionContext, view, viewData, tempData, output, new HtmlHelperOptions()); 
    viewContext.RouteData = _context.GetRouteData(); //set route data here 

    var task = view.RenderAsync(viewContext); 
    task.Wait(); 

    return output.ToString(); 
    } 
} 
+0

谢谢!它的工作无懈可击! –

+0

今天我需要这个修复,很高兴你记录下来。谢谢! –

+0

这救了我!这适用于ASP CORE 2.希望它可以帮助别人。 –

0

这是一个我在ASP.NET核心使用2.0

using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Linq; 
using Microsoft.AspNetCore.Http; 
using Microsoft.AspNetCore.Mvc; 
using Microsoft.AspNetCore.Mvc.Abstractions; 
using Microsoft.AspNetCore.Mvc.ModelBinding; 
using Microsoft.AspNetCore.Mvc.Razor; 
using Microsoft.AspNetCore.Mvc.Rendering; 
using Microsoft.AspNetCore.Mvc.ViewEngines; 
using Microsoft.AspNetCore.Mvc.ViewFeatures; 
using Microsoft.AspNetCore.Routing; 

namespace Website 
{ 
    public class RazorViewToStringRenderer 
    { 
     private readonly IHttpContextAccessor accessor; 
     private readonly IRazorViewEngine viewEngine; 
     private readonly IServiceProvider serviceProvider; 
     private readonly ITempDataProvider tempDataProvider; 

     public RazorViewToStringRenderer(
      IHttpContextAccessor accessor, 
      IRazorViewEngine viewEngine, 
      IServiceProvider serviceProvider, 
      ITempDataProvider tempDataProvider) 
     { 
      this.accessor = accessor; 
      this.viewEngine = viewEngine; 
      this.serviceProvider = serviceProvider; 
      this.tempDataProvider = tempDataProvider; 
     } 

     public string RenderViewToString<TModel>(string viewLocation, TModel model) 
     { 
      HttpContext httpContext = accessor.HttpContext; 

      httpContext.RequestServices = serviceProvider; 

      ActionContext actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor()); 

      IView view = FindView(actionContext, viewLocation); 

      using (StringWriter stringWriter = new StringWriter()) 
      { 
       ViewDataDictionary<TModel> viewDataDictionary = new ViewDataDictionary<TModel>(
        new EmptyModelMetadataProvider(), 
        new ModelStateDictionary()); 

       viewDataDictionary.Model = model; 

       TempDataDictionary tempDataDictionary = new TempDataDictionary(
        actionContext.HttpContext, 
        tempDataProvider); 

       HtmlHelperOptions htmlHelperOptions = new HtmlHelperOptions(); 

       ViewContext viewContext = new ViewContext(
        actionContext, 
        view, 
        viewDataDictionary, 
        tempDataDictionary, 
        stringWriter, 
        htmlHelperOptions); 

       viewContext.RouteData = accessor.HttpContext.GetRouteData(); 

       view.RenderAsync(viewContext).Wait(); 

       return stringWriter.ToString(); 
      } 
     } 

     private IView FindView(ActionContext actionContext, string viewLocation) 
     { 
      ViewEngineResult getViewResult = viewEngine.GetView(null, viewLocation, true); 

      if (getViewResult.Success) 
      { 
       return getViewResult.View; 
      } 

      ViewEngineResult findViewResult = viewEngine.FindView(actionContext, viewLocation, true); 

      if (findViewResult.Success) 
      { 
       return findViewResult.View; 
      } 

      IEnumerable<string> searchedLocations = getViewResult.SearchedLocations.Concat(findViewResult.SearchedLocations); 

      string message = string.Join(
       Environment.NewLine, 
       new[] { $"Unable to find view '{viewLocation}'. The following locations were searched:" }.Concat(searchedLocations)); ; 

      throw new Exception(message); 
     } 
    } 
} 

记得在Startup.cs - >公共无效ConfigureServices(IServiceCollection serviceCollection)来添加这个

serviceCollection.AddSingleton<RazorViewToStringRenderer>(); 
相关问题