Asp.net 发布时发送电子邮件,但不发送开发电子邮件

Asp.net email sending on publish but not development

我正在使用 asp.net mvc 开发应用程序。我需要在填充操作时发送电子邮件。

public class MyController : Controller{

   public ActionResult Create(string name){

        // create and save to database

        // if success 
        // select admin emails from database.
        // create email content and subject.
        // send email to admins.
   }
}

但是我想在发布我的项目后自动激活发送机制。在开发中,我不需要在创建操作时发送电子邮件。

是否有任何设置可以做到这一点?

您可以使用 HttpRequest.IsLocal 属性.

public class MyController : Controller
{
   public ActionResult Create(string name)
   {
       if (HttpContext.Current.Request.IsLocal) { ... }
       else { ... }
   }
}

要处理这类场景,您应该使用依赖注入(我个人在 99.9% 的项目中都使用它,因为这是您可以对其进行单元测试的唯一方法)。依赖注入库(Autofac, Ninject, Castle Windsor, Simple Injector 和其他)允许您根据某些配置在 运行 时间基础上解决依赖关系。例如,您有一个负责发送电子邮件的通信服务:

public interface ICommuniucationService
{
    void SendEmail(....);
}

public class CommunicationService : ICommuniucationService
{
    public void SendEmail(...)
    {
        //real implementation of sending email
    }
}

public class FakeCommunicationService : ICommuniucationService
{
    public void SendEmail(...)
    { 
       //do nothing.
       return;
    }
}

我的控制器将有一个 ICommuniucationService 类型的私有 属性,它将由依赖注入库通过构造函数注入实例化:

public class MyController : Controller{

   //this will be resolved in runtime(either CommuniucationService or FakeCommunicationService )
   private readonly ICommuniucationService EmailSvc;

   // Use constructor injection for the dependencies
   public MyController(ICommuniucationService svc) {
       this.EmailSvc= svc;       
   }

   public ActionResult Create(string name){

        // create and save to database

        // if success 
        // select admin emails from database.
        // create email content and subject.

        this.EmailSvc.SendEmail(...)

        //The action code doesn't change neither for 
   }
}

配置依赖项注入容器时,您可以这样做(Simple injector example 类似于此):

protected void Application_Start(object sender, EventArgs e) {       
    var container = new Container();  
#if DEBUG
   container.Register<ICommuniucationService, FakeCommuniucationService>(Lifestyle.Singleton); 
#else
   container.Register<ICommuniucationService, CommuniucationService>(Lifestyle.Singleton); 
#endif         

    container.Verify();
    DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
}

因此,使用此配置,当您的项目 运行 处于 DEBUG 模式时,您正在注册 FakeCommuniucationService,它不会发送电子邮件,而当您 运行 处于 RELEASE 模式时(您发布应用程序时应使用)真实 CommuniucationService 已注册