2017-07-09 13 views
0

電子メールを送信するプロジェクトに取り組んでいます.Razorを使用してHTMLテンプレートを作成したいのですが、オンラインで見たチュートリアルやドキュメントはすべて、Razorを使用してリクエストに応じてビューを返す方法しか示していません。私はHTMLをレンダリングし、それを私の電子メール送信コードに渡したいと思います。これは可能ですか?または、誰かがドットネットコアで動作する別のテンプレートエンジンを認識していますか?カミソリのテンプレートを文字列にコンパイルすることはできますか?

答えて

0

私はあなたが探しているものはRendering Razor to stringだと思っています。また、IView(私は1年以上に数回MVCに触れているのでここでは少し間違っているかもしれません)を使って、あなたはメモリビューを表示し、それをレンダリングして(ファイルの@ディレクティブを置き換えることもできます)、それを削除します。コードの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()); 
     } 
    } 
} 

ビューモデルクラス:

このサンプルで
+0

私は、これはdotnetcoreのために働くとは思いません –

0

は、あなたがあなたの目標のために必要なすべてを見つけるかもしれません

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>(); 
     } 
    } 
} 
関連する問題