WCF服务返回400 Bad Request

我有这个应用程序在本地和部署时使用.mdf SQL Express数据库文件(我通常用于测试目的)。 但是,当我将其更改为与我们的SQL Server 2008一起使用时,应用程序可以正常工作,但服务却没有。

例如,如果在我的代码页面后面我有一个按钮,将数据添加到这样的表,它可以正常工作:

public static string connString = @"Data Source=server1;Initial Catalog=Project;Integrated Security=True"; protected void btnAddProj_Click(object sender, EventArgs e) { using (var sqlc = new SqlConnection(connString)) { sqlc.Open(); var cmd = sqlc.CreateCommand(); int intProjectID; // Add the project info to the database cmd.CommandText = "INSERT INTO tblProject VALUES(@ProjName,@ProjTeam,@ProjStart,@ProjEnd)"; cmd.Parameters.Add("ProjName", System.Data.SqlDbType.NVarChar).Value = txtProjName.Text; cmd.Parameters.Add("ProjTeam", System.Data.SqlDbType.Int).Value = ddlTeamSupported.SelectedValue; cmd.Parameters.Add("ProjStart", System.Data.SqlDbType.NVarChar).Value = txtStartDate.Text; cmd.Parameters.Add("ProjEnd", System.Data.SqlDbType.NVarChar).Value = txtEndDate.Text; cmd.ExecuteNonQuery(); } } 

我的web.config设置为在该服务器上使用模拟,并且一切运行良好。 但是,对于我的服务,查询似乎没有返回任何内容,我收到400 Bad Request错误。

jquery的代码是:

 $.ajax({ type: "POST", async: false, url: "Services/ProjectService.svc/test", contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { console.log(data); } }); 

而对于服务:

 [ServiceContract] public interface IProjectService { [OperationContract] [WebInvoke(ResponseFormat = WebMessageFormat.Json)] ArrayList test(); } public static string connString = @"Data Source=server1;Initial Catalog=Project;Integrated Security=True"; public ArrayList test() { var sqlc = new SqlConnection(connString); sqlc.Open(); var cmd = sqlc.CreateCommand(); cmd.CommandText = "SELECT ProjectID FROM tblProject"; var reader = cmd.ExecuteReader(); ArrayList temparray = new ArrayList(); while (reader.Read()) { temparray.Add(reader[0]); } sqlc.Close(); return temparray; } 

如果不是查询数据库而是让服务只返回静态数据,那么它可以正常工作。 当应用程序的其余代码工作时,什么可能导致我的服务无法连接到数据库?

来自托管WCF服务的数据库连接被视为远程连接,因此请确保您的连接字符串指定了身份validation方法。 因此,请尝试在连接字符串中使用Integrated Security = SSPI,如果不起作用,请确保将应用程序池的标识设置为对SQL Server具有权限的域帐户。 🙂

您可能没有完全按照服务期望的那样设置HTTP标头,或者按照预期的顺序设置HTTP标头。

这是我如何调试它:

  1. 使用SvcUtil .exe创建快速测试客户端。
  2. 安装Fiddler ,将其打开。
  3. 使用瘦客户端调用服务操作。
  4. 使用Web应用程序调用相同的服务操作
  5. 查看Fiddler中针对每个请求的完整HTTP请求。 比较他们。 找出您的AJAX调用的不同之处,并解决差异,使其与生成的客户端使用的内容相匹配。

这可能是你正在进行POST,但服务期待GET。

尝试指定该方法应该是POST:

 [WebInvoke(Method = "POST", UriTemplate = "", ResponseFormat = WebMessageFormat.Json)] 

另一个可能是您正在使用可信连接。 这意味着安全上下文是应用程序池的标识(如果使用默认值)。 然后,您将使用无法访问其他计算机上的数据库的本地帐户建立与数据库的连接。

奇怪的是,根据错误信息,它应该是第一个解释,但根据您的描述,它将是第二个。