Search code examples
asp.netsql-serverasp.net-web-apisqlconnectionsqlcommand

Web API to connect to SQL Server and return response in JSON


I am trying to create a Web API that queries the SQL Server and returns the response in a JSON. Below is what I am trying

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

But looks like the return type ResponseMessage is not matching the HttpResponseMessage how can I connect the SQL server qand return the query response in JSON.


Solution

  • ResponseMessage returns IHttpActionResult derived ResponseMessageResult,

    ResponseMessageResult ResponseMessage(HttpResponseMessage response);
    

    so either update function result accordingly

     public IHttpActionResult Getdetails(string ROOM)
    

    or don't use ResponseMessage

    return response;