Asp.net电子邮件发送发布但不发展

时间:2016-04-04 06:00:07

标签: c# asp.net asp.net-mvc smtpclient

我正在使用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.
   }
}

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

有没有设置可以做到这一点?

2 个答案:

答案 0 :(得分:1)

您可以使用HttpRequest.IsLocal属性。

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

答案 1 :(得分:0)

要处理这种情况,你应该使用依赖注入(我个人在99.9%的项目中使用它,因为这是你可以对它进行单元测试的唯一方法)。依赖注入库(AutofacNinjectCastle WindsorSimple 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已注册

相关问题