我一直在尝试在我的MVC5网站上使用Postal。当我在我的网页上托管一个子网站,即http://localhost/Subsite我收到错误
我已将其调试到创建ControllerContext时未正确设置HttpContext。由于我从Hangfire运行Postal,因此HttpContext.Current始终为null。 Postal使用以下代码创建ContollerContext。
ControllerContext CreateControllerContext()
{
// A dummy HttpContextBase that is enough to allow the view to be rendered.
var httpContext = new HttpContextWrapper(
new HttpContext(
new HttpRequest("", UrlRoot(), ""),
new HttpResponse(TextWriter.Null)
)
);
var routeData = new RouteData();
routeData.Values["controller"] = EmailViewDirectoryName;
var requestContext = new RequestContext(httpContext, routeData);
var stubController = new StubController();
var controllerContext = new ControllerContext(requestContext, stubController);
stubController.ControllerContext = controllerContext;
return controllerContext;
}
string UrlRoot()
{
var httpContext = HttpContext.Current;
if (httpContext == null)
{
return "http://localhost";
}
return httpContext.Request.Url.GetLeftPart(UriPartial.Authority) +
httpContext.Request.ApplicationPath;
}
如何指定UrlRoot,以便不是拉出默认的localhost来根据我的子网站提取它?
答案 0 :(得分:1)
我按照http://docs.hangfire.io/en/latest/tutorials/send-email.html的说明发送了我的电子邮件。本教程中的方法如下
public static void NotifyNewComment(int commentId)
{
// Prepare Postal classes to work outside of ASP.NET request
var viewsPath = Path.GetFullPath(HostingEnvironment.MapPath(@"~/Views/Emails"));
var engines = new ViewEngineCollection();
engines.Add(new FileSystemRazorViewEngine(viewsPath));
var emailService = new EmailService(engines);
// Get comment and send a notification.
using (var db = new MailerDbContext())
{
var comment = db.Comments.Find(commentId);
var email = new NewCommentEmail
{
To = "yourmail@example.com",
UserName = comment.UserName,
Comment = comment.Text
};
emailService.Send(email);
}
}
我发现问题是FileSystemRazorViewEngine没有被邮政使用。为了实现这一点,我必须确保FileSystemRazorViewEngine是可用的第一个引擎。然后我将其删除,因为我不希望它成为默认引擎。以下是我更新的方法。
public static void NotifyNewComment(int commentId)
{
// Prepare Postal classes to work outside of ASP.NET request
var viewsPath = Path.GetFullPath(HostingEnvironment.MapPath(@"~/Views/Emails"));
var eng = new FileSystemRazorViewEngine(viewsPath));
ViewEngines.Engines.Insert(0, eng);
var emailService = new EmailService(engines);
// Get comment and send a notification.
using (var db = new MailerDbContext())
{
var comment = db.Comments.Find(commentId);
var email = new NewCommentEmail
{
To = "yourmail@example.com",
UserName = comment.UserName,
Comment = comment.Text
};
emailService.Send(email);
ViewEngines.Engines.RemoveAt(0)
}
}