代码之家  ›  专栏  ›  技术社区  ›  trx

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

  •  1
  • trx  · 技术社区  · 6 年前

    我正在尝试创建一个webapi来查询sqlserver并以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返回查询响应。

    2 回复  |  直到 6 年前
        1
  •  2
  •   Nkosi    6 年前

    ResponseMessage 退货 IHttpActionResult 派生 ResponseMessageResult ,

    ResponseMessageResult ResponseMessage(HttpResponseMessage response);
    

     public IHttpActionResult Getdetails(string ROOM)
    

    或者不使用 响应消息

    return response;
    
        2
  •  0
  •   Angel Dinev    6 年前

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

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