تهیه قالب برای ارسال ایمیلها در ASP.NET Core توسط Razor Viewها
نویسنده: وحید نصیری
تاریخ: ۱۳۹۵/۱۰/۰۶ ۲۰:۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
using Microsoft.AspNetCore.Http;
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.Mvc;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.DependencyInjection;
using System.IO;
using System.Threading.Tasks;
using System;
namespace WebToolkit
{
public static class RazorViewToStringRendererExtensions
{
public static IServiceCollection AddRazorViewRenderer(this IServiceCollection services)
{
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddScoped<IViewRendererService, ViewRendererService>();
return services;
}
}
public interface IViewRendererService
{
Task<string> RenderViewToStringAsync(string viewNameOrPath);
Task<string> RenderViewToStringAsync<TModel>(string viewNameOrPath, TModel model);
}
/// <summary>
/// Modified version of: https://github.com/aspnet/Entropy/blob/dev/samples/Mvc.RenderViewToString/RazorViewToStringRenderer.cs
/// </summary>
public class ViewRendererService : IViewRendererService
{
private readonly IRazorViewEngine _viewEngine;
private readonly ITempDataProvider _tempDataProvider;
private readonly IServiceProvider _serviceProvider;
private readonly IHttpContextAccessor _httpContextAccessor;
public ViewRendererService(
IRazorViewEngine viewEngine,
ITempDataProvider tempDataProvider,
IServiceProvider serviceProvider,
IHttpContextAccessor httpContextAccessor)
{
_viewEngine = viewEngine;
_tempDataProvider = tempDataProvider;
_serviceProvider = serviceProvider;
_httpContextAccessor = httpContextAccessor;
}
public Task<string> RenderViewToStringAsync(string viewNameOrPath)
{
return RenderViewToStringAsync(viewNameOrPath, string.Empty);
}
public async Task<string> RenderViewToStringAsync<TModel>(string viewNameOrPath, TModel model)
{
var actionContext = getActionContext();
var viewEngineResult = _viewEngine.FindView(actionContext, viewNameOrPath, isMainPage: false);
if (!viewEngineResult.Success)
{
viewEngineResult = _viewEngine.GetView("~/", viewNameOrPath, isMainPage: false);
if (!viewEngineResult.Success)
{
throw new FileNotFoundException($"Couldn't find '{viewNameOrPath}'");
}
}
var view = viewEngineResult.View;
using (var output = new StringWriter())
{
var viewDataDictionary = new ViewDataDictionary<TModel>(new EmptyModelMetadataProvider(), new ModelStateDictionary())
{
Model = model
};
var viewContext = new ViewContext(
actionContext,
view,
viewDataDictionary,
new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),
output,
new HtmlHelperOptions());
await view.RenderAsync(viewContext).ConfigureAwait(false);
return output.ToString();
}
}
private ActionContext getActionContext()
{
var httpContext = _httpContextAccessor?.HttpContext;
if (httpContext != null)
{
return new ActionContext(httpContext, httpContext.GetRouteData(), new ActionDescriptor());
}
httpContext = new DefaultHttpContext { RequestServices = _serviceProvider };
return new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
}
}
} {
"dependencies": {
"Microsoft.AspNetCore.Mvc.ViewFeatures": "1.1.0",
"Microsoft.AspNetCore.Mvc.Razor": "1.1.0"
}
} public void ConfigureServices(IServiceCollection services)
{
services.AddRazorViewRenderer();
} public class RenderController : Controller
{
private readonly IViewRendererService _viewRenderService;
public RenderController(IViewRendererService viewRenderService)
{
_viewRenderService = viewRenderService;
}
public async Task<IActionResult> RenderInviteView()
{
var viewModel = new InviteViewModel
{
UserId = "1",
UserName = "Vahid"
};
var emailBody = await _viewRenderService.RenderViewToStringAsync("EmailTemplates/Invite", viewModel).ConfigureAwait(false);
//todo: send emailBody
return Content(emailBody);
}
} <!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Language" content="fa" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type='text/css'>
.main {
font-size: 9pt;
font-family: Tahoma;
}
</style>
</head>
<body bgcolor="whitesmoke" style="font-size: 9pt; font-family: Tahoma; background-color: whitesmoke; direction: rtl;">
<div class="main">@RenderBody()</div>
</body>
</html> @using Sample.ViewModels
@model RegisterEmailConfirmationViewModel
@{
Layout = "~/Views/EmailTemplates/_EmailsLayout.cshtml";
}
با سلام
<br />
اکانت شما با مشخصات ذیل ایجاد گردید:
.... <a style="direction:ltr" href="@Url.Action("Index", "Home", values: new { area = "" }, protocol: this.Context.Request.Scheme)">@Model.EmailSignature</a> <style type="text/css">
@font-face{
font-family:'Open Sans';
font-style:normal;
font-weight:400;
src:local('Open Sans'), local('OpenSans'), url('http://fonts.gstatic.com/s/opensans/v10/cJZKeOuBrn4kERxqtaUH3bO3LdcAZYWl9Si6vvxL-qU.woff') format('woff');
}
</style>
<!--[if mso]>
<style type="text/css">
.fallback-text {
font-family: Arial, sans-serif;
}
</style>
<![endif]--> <td class="fallback-text" style="font-family: 'Open Sans', Arial, sans-serif;">Open sans font for all!</td>
PM> Install-Package DNTCommon.Web.Core
System.AggregateException: 'Some services are not able to be constructed' InvalidOperationException: Error while validating the service descriptor 'ServiceType: Blog.Core.Services.Interfaces.IUserService Lifetime: Transient ImplementationType: Blog.Core.Services.UserService': Unable to resolve service for type 'Microsoft.AspNetCore.Mvc.Razor.IRazorViewEngine' while attempting to activate 'Blog.Core.Convertors.ViewRendererService'. InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Mvc.Razor.IRazorViewEngine' while attempting to activate 'Blog.Core.Convertors.ViewRendererService'.
@model string <div>@Model</div> <div><CutumTagHelper asp-id="1000" /></div>
... @Html.Raw(Model.HtmlData) ....
... @Html.SomeNameLikeRenderedRaw(Model.HtmlData,Model.SomeDataAsDynamicViewModel) ....
var viewEngineResult = _viewEngine.FindView(actionContext, viewNameOrPath, isMainPage: false);
if (!viewEngineResult.Success)
{
viewEngineResult = _viewEngine.GetView("~/", viewNameOrPath, isMainPage: false);
if (!viewEngineResult.Success)
{
throw new FileNotFoundException($"Couldn't find '{viewNameOrPath}'");
}
}
var view = viewEngineResult.View; var view = CreateViewFromString(@"@model int <div class="AAA">@Model</div>");