您不需要伪造 httpcontext,只需打破控制器与ActionMailer
. 我给你写了一些包装。
邮件程序.cs:
public interface IMailer
{
void SendMail(string viewName, IEnumerable<string> to, string subject, IEnumerable<string> replayTo);
void SendMail(string viewName, object model, IEnumerable<string> to, string subject,
IEnumerable<string> replayTo);
void SendMail(string viewName, IEnumerable<string> to, string from, string subject, IEnumerable<string> replayTo);
void SendMail(string viewName, object model, IEnumerable<string> to, string from, string subject,
IEnumerable<string> replayTo);
}
public class Mailer : MailerBase, IMailer
{
public void SendMail(string viewName, IEnumerable<string> to, string subject,
IEnumerable<string> replayTo = null)
{
foreach (var email in to)
{
To.Add(email);
}
Subject = subject;
if (replayTo != null)
foreach (var email in replayTo)
{
ReplyTo.Add(email);
}
Email(viewName).Deliver();
}
public void SendMail(string viewName, object model, IEnumerable<string> to, string subject,
IEnumerable<string> replayTo = null)
{
foreach (var email in to)
{
To.Add(email);
}
Subject = subject;
if (replayTo != null)
foreach (var email in replayTo)
{
ReplyTo.Add(email);
}
Email(viewName, model).Deliver();
}
public void SendMail(string viewName, IEnumerable<string> to, string from, string subject,
IEnumerable<string> replayTo)
{
foreach (var email in to)
{
To.Add(email);
}
From = from;
Subject = subject;
if (replayTo != null)
foreach (var email in replayTo)
{
ReplyTo.Add(email);
}
Email(viewName).Deliver();
}
public void SendMail(string viewName, object model, IEnumerable<string> to, string from, string subject,
IEnumerable<string> replayTo)
{
foreach (var email in to)
{
To.Add(email);
}
From = from;
Subject = subject;
if (replayTo != null)
foreach (var email in replayTo)
{
ReplyTo.Add(email);
}
Email(viewName, model).Deliver();
}
}
要使用包装器,请使用 Ninject 或您想要的任何库绑定他并在控制器中使用它。
NinjectWebCommon.cs:
_kernel.Bind<IMailer>().To<Mailer>();
邮件控制器.cs:
private readonly IMailer _mailer;
public MailController(IMailer mailer) {
_mailer = mailer;
}
_mailer.SendMail("Forgot", new ForgotModel
{
UserName = membershipUser.UserName,
Email = user.Email,
Password = membershipUser.ResetPassword()
}, new List<string> { model.Email }, _myEmail, "Your password", new List<string>());