WCF IIS SQL问题

时间:2011-04-08 14:30:04

标签: sql-server wcf iis

我有本地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测试客户端上测试调用时,所有方法都按原样运行。

当使用VS向导(发布 - >本地IIS - > MyTestWeb站点)将服务发布到本地IIS时,我在尝试调用getFirstName()时遇到错误(SQL的身份验证方法是Windows身份验证)。

其他方法:

CompositeType GetDataUsingDataContract(CompositeType composite); 

string GetData(int value);

在VS开发服务器和本地IIS服务器上都能完美运行。

谢谢。

4 个答案:

答案 0 :(得分:1)

此外,从后端检索单个值时,最合适的使用方法可能是“ExecuteScalar”,它是专门为名称所暗示的任务设计的。

答案 1 :(得分:0)

看看我对这个问题的回答:WCF service works in cassini, but not in IIS

看起来你有同样的问题。

答案 2 :(得分:0)

是的,这可能是权限。确保您的站点运行的用户具有对SQL Server数据库的权限 - 例如,NT Authority \ SYSTEM(这取决于您的IIS版本)。

答案 3 :(得分:0)

很有可能,您的错误发生是因为您使用集成安全性连接到SQL Server Express,而在IIS中,这意味着运行IIS的身份,并且该帐户很可能在SQL Server实例上获得许可。

另一个建议:你应该改进你的ADO.NET代码!

  • 使用using(.....) { .... }块来保护您的可支配实体(特别是在WCF环境中很重要!)

  • 不要仅为了读取单个列值而创建SqlDataAdapterDataTable ......

我的推荐是这样的:

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;
}

这不是解决您当前的问题,但它可以帮助您避免未来(并且难以找到/跟踪)的问题!