2

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.

1
  • ResponseMessage returns IHttpActionResult, so either update function result or don't use ResponseMessage Commented Oct 10, 2018 at 15:09

2 Answers 2

2

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;
Sign up to request clarification or add additional context in comments.

Comments

0

You may use

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.