I have tried other solutions posted to stackoverflow and have found none that work, here is my problem.
So I want to send an email using hangfire through my MVC application, this works on my local machine but when I upload it to a remote server I get the following error on hangfire:
The virtual path '/' maps to another application, which is not allowed
This is the code I use to send the email:
foreach (var EmailEntry in EmailEntries)
{
var email = new EmailTemplateModel
{
ViewName = "EmailTemplateModel",
FromAddress = "donotreply@emailservice.com",
EmailAddress = EmailEntry,
Subject = "Task Report",
Date = Dates,
Task = DatesAndTasks,
};
email.Send();
}
When I use the 'ViewName' method it returns '~/Views/Emails' on my local machine.
Inside of the Send() method:
// Summary:
// Convenience method that sends this email via a default EmailService.
public void Send();
Application structure in IIS:
Server > Sites > Default > MyApplication
Issue raised by JodyL's solution below:
StructureMapDependencyScope.get_CurrentNestedContainer()
Solution:
Edited the following code in 'StructureMapDependencyScope' class:
Before:
public IContainer CurrentNestedContainer {
get {
return (IContainer)HttpContext.Items[NestedContainerKey];
}
set {
HttpContext.Items[NestedContainerKey] = value;
}
}
After:
public IContainer CurrentNestedContainer {
get {
IContainer container = null;
if (HttpContext != null)
container = (IContainer)HttpContext.Items[NestedContainerKey];
return container;
}
set {
HttpContext.Items[NestedContainerKey] = value;
}
}
Before:
private HttpContextBase HttpContext {
get {
var ctx = Container.TryGetInstance<HttpContextBase>();
return ctx ?? new HttpContextWrapper(System.Web.HttpContext.Current);
}
}
After:
private HttpContextBase HttpContext {
get {
var ctx = Container.TryGetInstance<HttpContextBase>();
if (ctx == null && System.Web.HttpContext.Current == null)
return null;
return ctx ?? new HttpContextWrapper(System.Web.HttpContext.Current);
}
}
This problem is probably caused because HTTPContext is not available to Postal when using Hangfire. If HTTPContext.Current is null, Postal uses http://localhost as the URL, which doesn't map to your application location. In order to get around this problem, you can use FileSystemRazorViewEngine when sending the email and pass it the path of your email template.
See the answer to this question for details on how to achieve this. Using Postal and Hangfire in Subsite