【发布时间】:2015-12-01 06:28:03
【问题描述】:
我创建了一个使用 ASP.net 和 C# 连接到外部 SQL Server 2012 的 Web api。我的连接字符串是 myConnection.ConnectionString = "Data Source=./PALLAVI-PC/SQLEXPRESS;Initial Catalog=StudentDB;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework";
代码中似乎没有错误。但是当我部署服务并尝试在提琴手上提取记录时,我收到 404 错误。 GET 网址是localhost:xxxxx/api/student/1
我在下面发布代码:
StudentController.cs
//api/student/id
[HttpGet]
[ActionName("GetStudentByID")]
public Student Get(int id)
{
//SQL Reader
SqlDataReader reader = null;
//SQL Connection class
SqlConnection myConnection = new SqlConnection();
//creating the connection string
myConnection.ConnectionString = "Data Source=./PALLAVI-PC/SQLEXPRESS;Initial Catalog=StudentDB;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework";
//SQL Commands class
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.CommandType = System.Data.CommandType.Text;
//sql query
sqlCmd.CommandText = "Select * from Students where Roll_Number=" + id + ";";
sqlCmd.Connection = myConnection;
//opening the connection
myConnection.Open();
//extracting the record
reader = sqlCmd.ExecuteReader();
//object of class student
Student myStudent = null;
while (reader.Read())
{
myStudent = new Student();
myStudent.Roll_Number = Convert.ToInt32(reader.GetValue(0));
myStudent.FirstName = reader.GetValue(1).ToString();
myStudent.LastName = reader.GetValue(2).ToString();
myStudent.Class = Convert.ToInt32(reader.GetValue(3));
myStudent.Gender = reader.GetValue(4).ToString();
}
return myStudent;
//close connection
myConnection.Close();
}
如果我在连接字符串中将斜杠更改为正向,我会收到错误unrecognized character。
【问题讨论】:
-
尝试访问
localhost:xxxxx/api/student/Get/1或localhost:xxxxx/api/student/GetStudentByID/1 -
您的 404 错误与数据库连接(或连接字符串)无关,因此请先关注为什么您的 URL 无法解析为任何内容。检查 IIS 设置以确保您的站点映射到包含您的代码的正确目录。检查绑定以确保您的端口使用正确。也许尝试在每个目录中放置一些示例 html 文件,以便在查看 web api 方法之前让您了解是否可以正确请求这些文件。另外,请检查您的请求是否也使用 http 和 https。同样,您的 IIS 设置在这里会有所帮助。
标签: c# asp.net rest asp.net-web-api2 fiddler