我有一个 jQuery UI 自动完成小部件,它通过调用 WebMethod 填充了对象列表。
我正在使用 C#、.NET 4.0。
这“在我的机器上工作”(在这里插入嘲笑的鼻息),但是当部署到服务器时,由于 WebMethod 失败,自动完成不会填充。我可以在 IE DevTools 的控制台窗口中看到以下错误:
Sys.Net.WebServiceFailedException: The server method 'SearchEmployees' failed with the following error: -- There was an error processing the request.
这是 Firebug 对 WebMethod 的 POST 响应中的错误:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.
我的页面上有一个 ScriptManager,EnablePageMethods="true"
我的方法是公开的并且具有[ScriptMethod()]
and[WebMethod]
属性。
检查了在 WebMethod 中调用的数据库的权限(有点争议,因为它甚至还没有进入数据库调用)。
检查我有using System.Web.Services;
和using System.Web.Script.Services;
检查 IIS 中给定 AppPool 的目标框架。
我的 javascript/jQuery:
PageMethods.SearchEmployees(function (results) {
$("#txtMessageFor").autocomplete({
source: results,
delay: 0,
autoFocus: true,
select: function (event, ui) {
$('#hfEmployeeEmail').val(ui.item.Email);
}
});
});
我在 CodeBehind 中的 WebMethod:
[ScriptMethod()]
[WebMethod]
public static List<Employee> SearchEmployees()
{
try
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT Name, Email FROM TableName";
cmd.Connection = conn;
conn.Open();
List<Employee> contacts = new List<Employee>();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
Employee employee = new Employee();
employee.label = sdr["Name"].ToString();
employee.value = sdr["Name"].ToString();
employee.Name = sdr["Name"].ToString();
employee.Email = sdr["Email"].ToString();
contacts.Add(employee);
}
}
conn.Close();
return contacts;
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
web.config 中的连接字符串
<connectionStrings>
<add name="ConnStr" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\FakeDBName.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient" />
</connectionStrings>
那么,任何人都可以帮助解决为什么 WebMethod 在部署时无法工作吗?