【发布时间】:2014-12-09 16:21:24
【问题描述】:
我是 C#/MVC 4 设置连接的菜鸟。直到现在,它总是在我开始工作之前就已经到位,所以我从来不用考虑它。但是,现在我需要建立与数据库的安全连接,并且没有任何工作示例可用作指导。
我目前正在尝试让SqlCredential documentation 中的示例工作,但无济于事。他们似乎在这个实现中遗漏了很多东西。
是否有我应该注意的更完整的指南?
这是我的代码:
// Web.config:
<connectionStrings>
<add name="Con" connectionString="Initial Catalog=myDB;Server=\\Server_name" providerName="System.Data.SqlClient" />
</connectionStrings>
// SearchController.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.SqlClient; // for SqlConnection & SqlCommand
using System.Configuration;
using System.Web.Configuration;
using System.Security;
Configuration config = Configuration.WebConfigurationManager.OpenWebConfiguration(Null);
ConnectionStringSettings connString = config.ConnectionStrings.ConnectionString[“Con”];
using (SqlConnection conn = new SqlConnection(connString.ConnectionString))
{
SecureString pwd = new SecureString();
pwd.Equals("PASSW0rd");
pwd.MakeReadOnly();
SqlCredential cred = new SqlCredential("my_user_id", pwd);
SqlCommand comm = new SqlCommand("SELECT * FROM Search", conn);
conn.Credential = cred;
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
}
WebConfigurationManager 出现错误:
“System.Configuration.Configuration”不包含定义 'WebConfigurationManager'
Null 有错误:
当前上下文中不存在名称“Null”
ConnectionString["Con"] 出现错误:
'System.Configuration.ConnectionStringsSection' 不包含 'ConnectionString' 的定义并且没有扩展接受第一个 论据...
另外,有没有更好的地方放置我的密码和用户名?在示例中,它使用文本框来接受这些作为输入,但在我的情况下,它们是已知的并且不会改变。
【问题讨论】:
-
尝试改用 System.Configuration.ConfigurationManager:msdn.microsoft.com/en-us/library/…。还要确保您的项目正在引用 System.Configuration 程序集。
标签: c# asp.net .net asp.net-mvc-4