Null HttpContext inside SendAsync method for IIdentityMessageService
I have very simple code that used to work before I tried to migrate to ASP.NET Identity. This is a real head cleaner. Using ASP.NET MVC 5 with ASP.NET Identity 2.1 (latest and greatest as of this writing) I have a "user forgot their email" action that does this:
await this.UserManager.SendEmailAsync(
user.Id,
AccountStrings.ForgotPasswordEmailTitle,
string.Format(AccountStrings.ForgotPasswordEmailMessage, callbackUrl));
My custom manager uses an implementation IIdentityMessageService
to send out emails, and my code is in Task SendAsync(IdentityMessage message)
. Within this method, I need an active Http context as I am using the Razor viewer to generate the email. Again, this has worked until today.
As of today, an exception is being thrown inside my method as an email is displayed saying that I have no active Http context. And sure HttpContext.Current
is null. It is not SendEmailAsync
null when called inside a controller action, it is not null after waiting in the continuation of the task, but it is null internally SendEmailAsync
.
I am using the correct <system.web><httpRuntime targetFramework="4.5.1" /></system.web>
flags inside web.config, all by the book. And now, after updating some component - be it a small version of ASP.NET MVC or a version of ASP.NET Identity - I don't know - HttpContext.Current
it is null.
I have an ugly "fix" where I keep the HttpContext.Current for a local var when my IdentityMessageService is instantiated and set the current HttpContext to that value while SendAsync is executing, which works, but it definitely smells like a pretty serious regression inside the ASP stack .NET.
Has anyone come across something similar?
source to share
I haven't run into this exact issue, but my gut feeling says HttpContext.Current
it shouldn't be used internally SendEmailAsync
, and this is not a bug, but an intentional implementation by the Identity Framework. I am assuming that a completely new thread is created just to send email and that this thread does not have access to HttpContext.Current, i.e. this thread is independent of the Http request / response.
So, I thought about decoupling your post from the HttpContext. And to help you with that, there is a RazorEngine project that allows you to work with Razor views, but without the HttpContext. This project is available via nuget:
Install-Package RazorEngine
And judging by the documentation , it's pretty easy to work with. I've never used it myself, so I can't go beyond what these web pages say.
source to share