asp.net – 从中​​等信任环境的Web.config读取system.net/mailSettings/smtp

我有一些继承的代码,它将SMTP服务器,用户名密码存储在Web.config的system.net/mailSettings/smtp部分中。

它曾经读过这样的:

Configuration c = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
MailSettingsSectionGroup settings = (MailSettingsSectionGroup)c.GetSectionGroup("system.net/mailSettings");
return settings.Smtp.Network.Host;

但是当我不得不部署到中等信任环境时,这是失败的。

所以按照this question的答案,我重写了如此使用GetSection():

SmtpSection settings = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
return settings.Network.Host;

但它仍然给我一个中等信任的SecurityException,并显示以下消息:

Request for ConfigurationPermission
Failed while attempting to access
configuration section
‘system.net/mailSettings/smtp’. To
allow all callers to access the data
for this section,set section
attribute ‘requirePermission’ equal
‘false’ in the configuration file
where this section is declared.

所以我尝试这个requirePermission属性,但是无法确定哪里放置它。

如果我将它应用到< smtp>节点,我得到一个ConfigurationError:“无法识别的属性’requirePermission’。请注意,属性名称区分大小写。

如果我将它应用到< mailSettings>节点,我仍然得到SecurityException。

有什么办法可以在中等信任下编程的这个配置部分或者我应该放弃它,并将设置移动到< appSettings>?

解决方法

requirePemission属性在< configSections>分组匹配web.config的部分,您有安全问题。

此外,您不需要使用代码发送邮件实际读取设置 – 您可以简单地使用一个空白的SmtpClient:

new SmtpClient.Send(MyMailMessage);

认情况下,它将使用config部分的设置进行发送。

相关文章

这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...
最近用到了CalendarExtender,结果不知道为什么发生了错位,...
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence cha...