asp.net - 用于连接 SQL Server 并以 JSON 格式返回响应的 Web API
问题描述
我正在尝试创建一个查询 SQL Server 并以 JSON 格式返回响应的 Web API。下面是我正在尝试的
[HttpGet]
public HttpResponseMessage Getdetails(string ROOM)
{
if (string.IsNullOrEmpty(ROOM))
{
return Request.CreateResponse(new { error = "Input paramete cannot be Empty or NULL" });
}
string commandText = "SELECT * from [TDB].[dbo].[results_vw] where ROOM = @ROOM_Data";
string connStr = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
var jsonResult = new StringBuilder();
using (SqlConnection connection = new SqlConnection(connStr))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("@ROOM_Data", SqlDbType.VarChar);
command.Parameters["@ROOM_Data"].Value = ROOM;
connection.Open();
var reader = command.ExecuteReader();
if (!reader.HasRows)
{
jsonResult.Append("[]");
}
else
{
while (reader.Read())
{
jsonResult.Append(reader.GetValue(0).ToString());
}
}
var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
response.Content = new StringContent(jsonResult.ToString());
return ResponseMessage(response);
}
但看起来返回类型与我如何连接 SQL 服务器 q 并以 JSON 格式返回查询响应ResponseMessage
不匹配。HttpResponseMessage
解决方案
ResponseMessage
返回IHttpActionResult
派生ResponseMessageResult
,
ResponseMessageResult ResponseMessage(HttpResponseMessage response);
所以要么相应地更新函数结果
public IHttpActionResult Getdetails(string ROOM)
或不使用ResponseMessage
return response;
推荐阅读
- javascript - 悬停一个 Div 会影响另一个容器中的元素
- python - 在 Python 中更改 Dataframe 的单列或多列的数据类型
- javascript - 如何开发多种不同语言的谷歌云功能,它们是实现面部识别系统的好选择吗?
- logging - 禁用特定 ansible-playbook 的日志记录
- xslt - 如何更改 For Each 循环中的 xsl 变量值
- c# - 从 MSSQL 读取空间数据更改格式(X 和 Y 坐标的顺序颠倒)
- javascript - 绘制 Highcharts - Angular 8 中的子弹图
- algorithm - 随机循环路径生成器
- spring-integration - Spring Integration - “currentComponent”(routerFlow)是单向“MessageHandler”,不适合配置“outputChannel”
- python - 初始化 DVC 存储库会引发错误