【问题标题】:What is the correct way to put parameters in web.config in MVC - ASP.NET在 MVC 中将参数放入 web.config 的正确方法是什么 - ASP.NET
【发布时间】:2014-10-15 15:58:12
【问题描述】:

我已经在 ASP.NET 中使用 MVC 4 创建了这个邮件发送表单。现在我想在我的 Web.config 中放置(使用)smpt、用户名、密码和端口号的参数。我已经尝试过这个解决方案:

在 Web.config 中:

<add key="smptserver" value="smptABC" />
<add key="username" value="usernameABC" />
<add key="password" value="passwordABC"/>
<add key="portNum" value="123"/>

在我的 Controller.cs 中有这个:

using System.Configuration;

...

string host = ConfigurationManager.AppSettings["smptserver"];
string user = ConfigurationManager.AppSettings["username"];
string pass = ConfigurationManager.AppSettings["password"];
string port = ConfigurationManager.AppSettings["portNum"];

using (var client = new SmtpClient
{
    Host = host,
    Port = port,
    EnableSsl = true,
    Credentials = new NetworkCredential(user, pass),
    DeliveryMethod = SmtpDeliveryMethod.Network
})
{ ...

我也找到了这个解决方案(都一样,但只有这个有所改变):

string host = ConfigurationSettings.AppSettings["smptserver"];
string user = ConfigurationSettings.AppSettings["username"];
string pass = ConfigurationSettings.AppSettings["password"];
string port = ConfigurationSettings.AppSettings["portNum"];

[other is same]

“ConfigurationManager”和“ConfigurationSettings”有什么区别? 这是用 Web.config 设置参数的正确方法吗?

感谢您的解释。

【问题讨论】:

  • 不推荐使用第二个解决方案,使用第一个。这只是检索数据的问题,而不是设置数据。
  • 您不应该将密码放入您的 web.config 文件中。请参阅asp.net/identity/overview/features-api/… 了解如何将它们移出。
  • tnx 回答 :) @RickAnd - MSFT

标签: asp.net-mvc asp.net-mvc-4 web-config


【解决方案1】:

根据the documentationConfigurationSettings 公开了已弃用(标记为“过时”)的功能。 (您的代码应该在编译时生成警告消息来表明这一点。如果不是,请重新打开警告。)

ConfigurationManager 是首选。

【讨论】:

    猜你喜欢
    • 2015-01-07
    • 2019-10-10
    • 1970-01-01
    • 2017-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-07
    • 2019-07-20
    相关资源
    最近更新 更多