我有本地IIS服务器,本地SQL服务器和WCF测试服务,有3个接口方法:
[OperationContract]
string GetData(int value);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
[OperationContract]
string getFirstName();
前两个是VS模板,我已经添加了getFirstName()
方法
{
//very basic
string connectionString = @"Data Source=.SqlExpress;Initial Catalog=ProjectDB;Integrated Security=True";
SqlConnection con = new SqlConnection(connectionString);
con.Open();
SqlCommand command = new SqlCommand("select * from messages;", con);
DataTable table = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(table);
con.close();
return table.Rows[0][3].ToString();
}
当我在VS的WCF测试客户端上测试调用时,所有方法都正常运行。
当服务发布到本地IIS与VS向导(发布->本地IIS -> MyTestWeb站点)我得到错误时,试图调用getFirstName()
(SQL的身份验证方法是windows身份验证)。
其他方法:
CompositeType GetDataUsingDataContract(CompositeType composite);
和
string GetData(int value);
在VS开发服务器和本地IIS服务器上都能完美工作。
谢谢。
进一步从后端检索单个值,最合适的方法可能是"ExecuteScalar",顾名思义,它是专门为任务设计的。
很可能,你的错误发生是因为你使用集成安全连接到SQL Server Express,而在IIS中,这意味着正在运行IIS的身份,并且该帐户很可能不在你的SQL Server实例上被允许。
另一个建议:你应该改进你的ADO。NET代码!
-
使用
using(.....) { .... }
块来保护您的一次性实体(特别是在WCF环境中很重要!) -
不要创建
SqlDataAdapter
和DataTable
只是为了读取单个列值......
我的建议是这样的:
public string GetFirstName()
{
string firstName = string.Empty;
string connectionString = @"Data Source=.SqlExpress;Initial Catalog=ProjectDB;Integrated Security=True";
using(SqlConnection con = new SqlConnection(connectionString))
using(SqlCommand command = new SqlCommand("SELECT FirstName FROM dbo.Messages", con))
{
con.Open();
using(SqlDataReader rdr = command.ExecuteReader())
{
if(rdr.Read())
{
firstName = rdr.GetString(0); // read column no. 0
}
rdr.Close();
}
con.close();
}
return firstName;
}
这并不能解决你当前的问题,但它可能会帮助你避免未来的问题(并且很难找到/跟踪)!
看看我对这个问题的回答:WCF服务可以在cassini中工作,但不能在IIS中工作
看起来你也有同样的问题
对,可能是权限。请确保您的站点运行的用户具有对SQL Server数据库的权限-例如,NT AuthoritySYSTEM(这取决于您的IIS版本)。