接收"值不能为空。参数名称:httpContext"从ASP MVC发送MVC Mailer电子邮件时

时间:2017-12-04 16:56:26

标签: asp.net-mvc mvcmailer

当我从服务器发送时,我的MVC Mailer实例失败了。我尝试发送电子邮件时收到错误initialValues

我的代码如下:

Value cannot be null.Parameter name: httpContext

它在 public static void SendApproval(TimeOffRequest request) { MailService mailer = new MailService(); mailer.ViewData.Model = request; MvcMailMessage mailMessage = new MvcMailMessage { Subject = $"PTO request approved for {request.StartTime} to {request.EndTime}", From = new MailAddress("calendar@company.com"), }; mailMessage.To.Add(new MailAddress(request.Requester.Email)); if (mailMessage.To.Count == 0) return; mailer.PopulateBody(mailMessage, "RequestApproved"); mailMessage.Send(); }

行上特别失败

从控制器端点的帖子调用它。为什么在这种情况下缺少上下文?我试图手动传递上下文,但也失败了。

继承堆栈跟踪的顶部:

mailer.PopulateBody(mailMessage, "RequestApproved");

1 个答案:

答案 0 :(得分:0)

MVCMailer的PopulateBody方法在MailerBase类中有3个参数和4个参数重载(3个参数版本实际上调用4个参数重载,masterName设置为null ):

// 3 arguments overload
public virtual void PopulateBody(MailMessage mailMessage, string viewName, Dictionary<string, string> linkedResources) 
{
    PopulateBody(mailMessage, viewName, null, linkedResources);
}

// 4 arguments overload
public virtual void PopulateBody(MailMessage mailMessage, string viewName, string masterName = null, Dictionary<string, string> linkedResources = null) 
{
    ...
}

根据调查结果,使用额外的null来填充不必要的方法参数,使用3或4个参数版本:

// 3 arguments
mailer.PopulateBody(mailMessage, "RequestApproved", null); 

// 4 arguments
mailer.PopulateBody(mailMessage, "RequestApproved", null, null);

由于可能的原因源自MailerBase类(在var routeData = RouteTable.Routes.GetRouteData(CurrentHttpContext); CurrentHttpContext传递空值的情况下),您可以看到HttpContextBase虚拟属性的空值检查的利用率this request

类似问题:

MvcMailer unit tests: System.ArgumentNullException httpContext cannot be null