【发布时间】:2016-05-02 05:02:01
【问题描述】:
我正在尝试自学一些有关 Web 服务的基础知识并设置一个简单的应用程序,该应用程序只访问 SQL 服务器并从数据库中提取一个项目。
但我在尝试连接时收到此错误:
“命名管道提供程序,错误:40 - 无法打开与 SQL Server 的连接)---> System.ComponentModel.Win32Exception:找不到网络路径”
我将此连接字符串用于其他解决方案,它可以正常工作,但不适用于 Web 服务,并且在搜索 Stack 时我找不到适合此问题的解决方案。
<connectionStrings>
<add name="Snafoo" connectionString="Data Source=HOCHBAUM|SQLEXPRESS; Initial Catalog=Snafoo;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
这里是网络服务:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace SnafooWebService
{
/// <summary>
/// Summary description for SnafooService
/// </summary>
[WebService(Namespace = "Snafoo")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class SnafooService : System.Web.Services.WebService
{
[WebMethod()]
public Snacks GetSnackByID(int ID)
{
//Retrieve connection String from Web.config
string cs = ConfigurationManager.ConnectionStrings["Snafoo"].ConnectionString;
//Create a SQL connection object
using (SqlConnection con = new SqlConnection(cs))
{
//This object executes stored procedure in SQL
SqlCommand cmd = new SqlCommand("spGetSnackByID", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter parameter = new SqlParameter("@Id", ID);
cmd.Parameters.Add(parameter);
Snacks snack = new Snacks();
//Opens the cconection
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
//Retrieve column values and populate properties of snack object
while (reader.Read())
{
snack.id = Convert.ToInt32(reader["ID"]);
snack.name = reader["name"].ToString();
snack.location = reader["location"].ToString();
}
return snack;
}
}
}
}
【问题讨论】:
-
"HOCHBAUM|SQLEXPRESS" 好像错了,试试"HOCHBAUM\SQLEXPRESS"
-
你有答案!有效!盯着它看了好几个小时,完全错过了,有第二双眼睛真好!
标签: asp.net sql-server web-services