【发布时间】:2012-08-28 05:40:28
【问题描述】:
我有一个 jQuery UI 自动完成小部件,它通过调用 WebMethod 填充了对象列表。
我正在使用 C#、.NET 4.0。
这个'在我的机器上工作'(在这里插入嘲笑的鼻息),但是当部署到服务器时,由于 WebMethod 失败,自动完成没有填充。我可以在 IE DevTools 的 Console 窗口中看到以下错误:
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()] 和[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 在部署时无法工作?
【问题讨论】:
-
请您检查一下,但由于您在最后抛出异常,因此您的连接字符串可能在部署环境中无效,并且在选择期间抛出异常。我认为这将是一个好主意,而不是抛出异常,将其记录在某个地方。我想你可以在这里看到更详细的问题。
-
@AndrásOttó 据我所知,它甚至没有到达连接字符串。我可以完全删除数据库,但我仍然收到相同的错误,这表明在此之前出现了问题。
-
试一试我可以说你可以关闭自定义错误模式,然后你可以看到更详细的异常。尝试在 webconfig 中应用
,这应该会为您提供正常的 ASP.NET 错误页面,如果我是对的,如果 webmethod 抛出异常,您可以看到更多然后。 (当然,如果您有机会尝试它)但不幸的是,如果没有它,如果您在 catch 中抛出一些东西,您的页面无论如何都不会显示任何详细的异常。 -
或者您可以尝试将 throw Exception 注释掉,看看会发生什么。
-
@AndrásOttó。没有。自定义错误关闭并且 throw 被注释掉了。没有页面错误。它不会崩溃,只是不会填充自动完成功能。
标签: asp.net jquery-ui-autocomplete webmethod