首页 > 解决方案 > 用于连接 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

标签: asp.netsql-serverasp.net-web-apisqlconnectionsqlcommand

解决方案


ResponseMessage返回IHttpActionResult派生ResponseMessageResult

ResponseMessageResult ResponseMessage(HttpResponseMessage response);

所以要么相应地更新函数结果

 public IHttpActionResult Getdetails(string ROOM)

或不使用ResponseMessage

return response;

推荐阅读