'IHttpContextAccessor returned null in / Scheme and Host
I have a job with a schedule inside this jobs I need to send an email every 5 min so I inject my service to get the data the difficulty is I need to send the link of the application inside email so here obligatory to use IHttpContextAccessor inside my class I injected this to access to context so this my code
private readonly IService _Service;
private readonly IHttpContextAccessor _contextAccessor;
private readonly ILogger _logger;
public SendEmailOverdueJob(Service Service, ILogger logger, IHttpContextAccessor contextAccessor)
{
_contextAccessor = contextAccessor;
_logger = logger;
}
public Task Execute(IJobExecutionContext context)
{
IEnumerable<ViewModel> Detail = null;
Detail = _Service.TaskOverdue();
if (Detail != null)
{
foreach (var item in Detail )
{
EmailModel viaEmailModel = new EmailModel()
{
ToName = item.FullName,
ToEmail = item.Email,
Subject = ConstantStrings.CreatedSubject,
FromEmail = null,
};
var htmlstring = GetEmailTemplete(ConstantStrings.DocumentRequestFromCreateHtml);
htmlstring = htmlstring.Replace("[toName]", Convert.ToString(item.FullName));
htmlstring = htmlstring.Replace("[TITLE]", Convert.ToString(item.Subject));
htmlstring = htmlstring.Replace("[subject]", ConstantStrings.CreatedSubject);
htmlstring = htmlstring.Replace("{detailPageLink}", _contextAccessor.HttpContext.Request.Scheme + "://" + _contextAccessor.HttpContext.Request.Host.ToString() + "/Request/Details?id=" + item.Id);
viaEmailModel.Body = htmlstring;
viaEmailModel.Body = htmlstring;
var res = EmailSender.SendEmail(viaEmailModel);
}
}
return Task.CompletedTask;
}
public string GetEmailTemplete(string templateName)
{
try
{
if (!String.IsNullOrEmpty(templateName))
{
var path = Path.Combine("wwwroot", "EmailHtmls");
var filePath = Path.Combine(path, templateName);
var htmlString = System.IO.File.ReadAllText(filePath);
htmlString = htmlString.Replace("{emailLogo}", _contextAccessor.HttpContext.Request.Scheme + "://" + _contextAccessor.HttpContext.Request.Host.ToString() + "/images/emaillogo.png");
return htmlString;
return htmlString;
}
}
catch (Exception ex)
{
_logger.LogError("Error - {exception_source} occured at {exception_datetime}", ex.ToString(), DateTime.UtcNow);
}
return String.Empty;
}
the probleme is _contextAccessor.HttpContext.Request.Scheme & _contextAccessor.HttpContext.Request.Host.ToString() returned null
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
