[英]WCF Service returns 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服務的數據庫連接被視為遠程連接,因此請確保您的連接字符串指定了身份驗證方法。 因此,請嘗試在連接字符串中使用Integrated Security = SSPI,如果該操作不起作用,請確保將您的應用程序池的標識設置為對SQL Server具有權限的域帳戶。 :)
這可能是因為您正在進行POST,但服務正在期待GET。
嘗試指定該方法應為POST:
[WebInvoke(Method = "POST", UriTemplate = "", ResponseFormat = WebMessageFormat.Json)]
另一個可能是您使用的是受信任的連接。 這意味着安全上下文是應用程序池的標識(如果使用默認值)。 然后,您將使用沒有其他計算機上數據庫訪問權限的本地帳戶建立與數據庫的連接。
奇怪的是,基於錯誤消息,它應該是第一個解釋,但是根據您的描述,它應該是第二個解釋。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.