2016-09-29 75 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>(); 
相關問題