webapi 带参数查询sqlserver 返回json 的例子
时间: 2023-10-03 07:03:01 浏览: 54
以下是一个基于Web API的带参数查询SQL Server并返回JSON数据的示例代码:
1. 首先,需要安装NuGet包“System.Data.SqlClient”,以便连接SQL Server数据库。
2. 在您的Web API项目中,创建一个控制器类(例如,名为“DataController”),并添加以下代码:
using System.Data.SqlClient;
using System.Web.Http;
namespace YourProject.Controllers
{
public class DataController : ApiController
{
[HttpGet]
public IHttpActionResult Get(int id)
{
string connectionString = "Data Source=YourServerName;Initial Catalog=YourDatabaseName;Integrated Security=True";
string query = "SELECT * FROM YourTableName WHERE Id = @Id";
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("@Id", id);
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
var result = new
{
Id = reader.GetInt32(reader.GetOrdinal("Id")),
Name = reader.GetString(reader.GetOrdinal("Name")),
Age = reader.GetInt32(reader.GetOrdinal("Age"))
};
return Json(result);
}
}
return NotFound();
}
}
}
}
}
}
3. 在上面的控制器代码中,我们使用了HTTP GET请求,并且通过“Get”方法接收一个“id”参数。
4. 在“Get”方法内部,我们首先创建了一个用于连接SQL Server的“SqlConnection”对象。
5. 然后,我们定义了一个SQL查询字符串,并使用“SqlCommand”对象来执行该查询,并使用“SqlParameter”对象将“id”参数传递给查询。
6. 接下来,我们使用“SqlDataReader”对象来遍历查询结果,并将结果封装在一个匿名对象中。
7. 最后,使用Web API的“Json”方法将结果返回为JSON格式。
这是一个基本的例子,您可以根据自己的需求进行修改和扩展。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)