SmtpClient and app.config system.net configuration

℡╲_俬逩灬. 提交于 2019-12-04 18:15:30

问题


I'm having an issue with a .NET 3.5 library I'm developing to send emails. I put the system.net configuration into app.config:

<system.net>
  <mailSettings>
    <smtp from="mail@domain.com">
      <network host="myserver.com" port="25" defaultCredentials="true" />
    </smtp>
  </mailSettings>
</system.net>

And I instantiate the SmtpClient without params:

SmtpClient client = new SmtpClient();

But the configuration is not read (I'm trying to test the library with NUnit) and I get a System.InvalidOperationException, because the configuration is not read and thus the host is null.

Shouldn't the configuration be read automatically?


回答1:


Make sure you add your configuration block (as shown above) to the {appName}.exe.config or web.config - the configuration for the class library is taken from one of those files at runtime, not from the app.config of the class library.




回答2:


I've just realized I'm definitely doing it the wrong way (there's also a similar post from John about it and the solution is there...).

The mailsettings is available only at the application level, so the test project should know about your settings to take them into account.

Thanks to John and Davide for pointing me to the right direction!



来源:https://stackoverflow.com/questions/7244589/smtpclient-and-app-config-system-net-configuration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!