我一直在尝试在我的 MVC5 站点上使用 Postal。当我将我的网页托管为子网站时,即http://localhost/子站点 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,而是根据我的子站点拉取它?
我按照这里的指示进行操作http://docs.hangfire.io/en/latest/tutorials/send-email.html 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 = "[email protected] /cdn-cgi/l/email-protection",
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 = "[email protected] /cdn-cgi/l/email-protection",
UserName = comment.UserName,
Comment = comment.Text
};
emailService.Send(email);
ViewEngines.Engines.RemoveAt(0)
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)