trx
trx

Reputation: 2157

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.

Upvotes: 2

Views: 1883

Answers (2)

Angel Dinev
Angel Dinev

Reputation: 489

You may use

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

which produces HttpResponseMessage object with 200(OK) Http status code + provided data object as a content.

Upvotes: 0

Nkosi
Nkosi

Reputation: 246998

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;

Upvotes: 2

Related Questions