我正在尝试使用 Hangfire 和 Postal 发送电子邮件,但我遇到了 HTTPContext 问题。如果我通过控制器执行拍摄,则发送没有问题,现在如果我通过 Hangfire 执行作业,则会生成预期。
代码启动.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddHangfire(configuration => configuration
.SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
.UseSimpleAssemblyNameTypeSerializer()
.UseRecommendedSerializerSettings()
.UseSqlServerStorage(Configuration.GetConnectionString("default"), new SqlServerStorageOptions
{
CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
QueuePollInterval = TimeSpan.Zero,
UseRecommendedIsolationLevel = true,
UsePageLocksOnDequeue = true,
DisableGlobalLocks = true
}));
services.Configure<EmailSenderOptions>(Configuration.GetSection("EmailSender"));
services.AddPostal();
services.AddTransient<IEmailSenderEnhance, EmailSender>();
services.AddHttpContextAccessor();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
var options = new DashboardOptions
{
Authorization = new[] { new HangFireAuthorizationFilter() }
};
app.UseHangfireDashboard("/hangfire", options);
app.UseHangfireServer();
RecurringJob.AddOrUpdate<NotificationServices>("SendNotify-", m => m.Notify(1), Cron.Daily);
}
代码 NotificationServices.cs
public class NotificationServices
{
private readonly IEmailSenderEnhance _emailSender;
private readonly Config _appConfig;
private readonly IHttpContextAccessor _httpContextAccessor;
public NotificationServices(IEmailSenderEnhance emailSender, IOptions<Config> optionsAccessor, IHttpContextAccessor httpContextAccessor)
{
_emailSender = emailSender;
if (optionsAccessor == null) throw new ArgumentNullException(nameof(optionsAccessor));
_appConfig = optionsAccessor.Value;
_httpContextAccessor = httpContextAccessor;
}
public void Notify(int messageId)
{
var listOSs = Task.Run(async () => await this.SendEmail(messageId));
}
public async Task SendEmail(int orderID)
{
var orderRy = new OrderRepository();
var order = orderRy.Get_By_ID(orderID);
try
{
var requestPath = new Postal.RequestPath
{
PathBase = _httpContextAccessor.HttpContext.Request.PathBase.ToString(),
Host = _httpContextAccessor.HttpContext.Request.Host.ToString(),
IsHttps = _httpContextAccessor.HttpContext.Request.IsHttps,
Scheme = _httpContextAccessor.HttpContext.Request.Scheme,
Method = _httpContextAccessor.HttpContext.Request.Method
};
var emailData = new Postal.Email("SendTest")
{
RequestPath = requestPath,
};
var emailsCopy = $"{order.Salesman.Email},{order.Salesman2.Email},";
emailData.ViewData["to"] = emailsCopy;
emailData.ViewData["Order"] = order;
await _emailSender.SendEmailAsync(emailData);
}
catch (Exception ex)
{
}
}
}
错误在 HttpContext 中:_httpContextAccessor.HttpContext.Request.PathBase.ToString()
是否可以通过 Postal 后台发送电子邮件?