2017-07-09 36 views
0

我正在開發一個發送電子郵件的項目,我想使用Razor創建HTML模板,但是我在網上看到的所有教程和文檔僅顯示了使用Razor響應請求返回視圖的方法。我想呈現HTML,然後將其傳遞給我的電子郵件發送代碼。這可能嗎?或者是否有人知道另一個模板引擎可以與dotnet core一起工作?可能將剃刀模板編譯爲字符串?

回答

0

我想你要找的是Rendering Razor to string,你也可以使用IView動態創建剃鬚刀字符串文件(我可能在這裏有點錯誤,因爲我已經觸摸MVC在一年多)來創建你的內存視圖,渲染它(也可以用來代替你的@指令在文件上)然後刪除它。

+0

我不認爲這適用於dotnetcore –

0

在此示例中,你可能會發現,你需要爲你的目標的一切:https://github.com/aspnet/Entropy/tree/master/samples/Mvc.RenderViewToString

的代碼示例:

RazorViewToString.cs

using System; 
using System.IO; 
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.ViewFeatures; 
using Microsoft.AspNetCore.Routing; 

namespace RenderRazorToString 
{ 
    public class RazorViewToString 
    { 
     private readonly IRazorViewEngine _viewEngine; 
     private readonly ITempDataProvider _tempDataProvider; 
     private readonly IServiceProvider _serviceProvider; 

     public RazorViewToString(
      IRazorViewEngine viewEngine, 
      ITempDataProvider tempDataProvider, 
      IServiceProvider serviceProvider) 
     { 
      _viewEngine = viewEngine; 
      _tempDataProvider = tempDataProvider; 
      _serviceProvider = serviceProvider; 
     } 

     public async Task<string> RenderViewToString<TModel>(string name, TModel model) 
     { 
      var actionContext = GetActionContext(); 

      var viewEngineResult = _viewEngine.FindView(actionContext, name, false); 

      if (!viewEngineResult.Success) 
      { 
       throw new InvalidOperationException(string.Format("Couldn't find view '{0}'", name)); 
      } 

      var view = viewEngineResult.View; 

      using (var output = new StringWriter()) 
      { 
       var viewContext = new ViewContext(
        actionContext, 
        view, 
        new ViewDataDictionary<TModel>(
         metadataProvider: new EmptyModelMetadataProvider(), 
         modelState: new ModelStateDictionary()) 
        { 
         Model = model 
        }, 
        new TempDataDictionary(
         actionContext.HttpContext, 
         _tempDataProvider), 
        output, 
        new HtmlHelperOptions()); 

       await view.RenderAsync(viewContext); 

       return output.ToString(); 
      } 
     } 

     private ActionContext GetActionContext() 
     { 
      var httpContext = new DefaultHttpContext 
      { 
       RequestServices = _serviceProvider 
      }; 

      return new ActionContext(httpContext, new RouteData(), new ActionDescriptor()); 
     } 
    } 
} 

視圖模型類:

EmailViewModel.cs

namespace RenderRazorToString 
{ 
    public class EmailViewModel 
    { 
     public string UserName { get; set; } 

     public string SenderName { get; set; } 
    } 
} 

和佈局,並查看文件:

查看/ _EmailLayout.cshtml

<!DOCTYPE html> 

<html> 
<body> 
    <div> 
     @RenderBody() 
    </div> 
    <footer> 
Thanks,<br /> 
@Model.SenderName 
    </footer> 
</body> 
</html> 

查看/ EmailTemplate.cshtml

@model RenderRazorToString.EmailViewModel 
@{ 
    Layout = "_EmailLayout"; 
} 

Hello @Model.UserName, 

<p> 
    This is a generic email about something.<br /> 
    <br /> 
</p> 

在控制檯應用程序,你只需需要初始化ialize一些服務,並將其命名爲:

Program.cs的

using System; 
using System.Diagnostics; 
using System.IO; 
using Microsoft.AspNetCore.Hosting; 
using Microsoft.AspNetCore.Hosting.Internal; 
using Microsoft.AspNetCore.Mvc.Razor; 
using Microsoft.Extensions.DependencyInjection; 
using Microsoft.Extensions.FileProviders; 
using Microsoft.Extensions.ObjectPool; 
using Microsoft.Extensions.PlatformAbstractions; 

namespace RenderRazorToString 
{ 
    public class Program 
    { 
     public static void Main() 
     { 
      // Initialize the necessary services 
      var services = new ServiceCollection(); 
      ConfigureDefaultServices(services); 
      var provider = services.BuildServiceProvider(); 

      var renderer = provider.GetRequiredService<RazorViewToString>(); 

      // Build a model and render a view 
      var model = new EmailViewModel 
      { 
       UserName = "User", 
       SenderName = "Sender" 
      }; 
      var emailContent = renderer.RenderViewToString("EmailTemplate", model).GetAwaiter().GetResult(); 

      Console.WriteLine(emailContent); 
      Console.ReadLine(); 
     } 

     private static void ConfigureDefaultServices(IServiceCollection services) 
     { 
      var applicationEnvironment = PlatformServices.Default.Application; 
      services.AddSingleton(applicationEnvironment); 

      var appDirectory = Directory.GetCurrentDirectory(); 

      var environment = new HostingEnvironment 
      { 
       WebRootFileProvider = new PhysicalFileProvider(appDirectory), 
       ApplicationName = "RenderRazorToString" 
      }; 
      services.AddSingleton<IHostingEnvironment>(environment); 

      services.Configure<RazorViewEngineOptions>(options => 
      { 
       options.FileProviders.Clear(); 
       options.FileProviders.Add(new PhysicalFileProvider(appDirectory)); 
      }); 

      services.AddSingleton<ObjectPoolProvider, DefaultObjectPoolProvider>(); 

      var diagnosticSource = new DiagnosticListener("Microsoft.AspNetCore"); 
      services.AddSingleton<DiagnosticSource>(diagnosticSource); 

      services.AddLogging(); 
      services.AddMvc(); 
      services.AddSingleton<RazorViewToString>(); 
     } 
    } 
}