Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/29.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net 连接到SQL Server并返回JSON响应的Web API_Asp.net_Sql Server_Asp.net Web Api_Sqlconnection_Sqlcommand - Fatal编程技术网

Asp.net 连接到SQL Server并返回JSON响应的Web API

Asp.net 连接到SQL Server并返回JSON响应的Web API,asp.net,sql-server,asp.net-web-api,sqlconnection,sqlcommand,Asp.net,Sql Server,Asp.net Web Api,Sqlconnection,Sqlcommand,我正在尝试创建一个Web API,用于查询SQL Server并以JSON格式返回响应。下面是我正在尝试的 [HttpGet] public HttpResponseMessage Getdetails(string ROOM) { if (string.IsNullOrEmpty(ROOM)) { return Request.CreateResponse(new { error = "Input paramete ca

我正在尝试创建一个Web API,用于查询SQL Server并以JSON格式返回响应。下面是我正在尝试的

 [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);
        }

但是看起来返回类型
ResponseMessage
HttpResponseMessage
不匹配。如何连接SQL server Q并以JSON返回查询响应。

ResponseMessage
返回
IHttpActionResult
派生
ResponseMessageResult

ResponseMessageResult ResponseMessage(HttpResponseMessage response);
因此,要么相应地更新函数结果

 public IHttpActionResult Getdetails(string ROOM)
或者不要使用
ResponseMessage

return response;
你可以用

return Request.CreateResponse(jsonResult.ToString());

它生成的HttpResponseMessage对象包含200(确定)Http状态代码+提供的数据对象作为内容。

ResponseMessage
返回
IHttpActionResult
,因此要么更新函数结果,要么不使用
ResponseMessage