Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

192
Views
How to create a webapi that returns sqldatareader data in c#?

I am using asp.net core. I need to display the data in the select dropdown in react from web api. WebApi GET method that returns SQL DataReader. Reader returns one row with prodid, prodname, and proddescr columns. Please help what the best way to write a get web api that uses SQL DataReader for filling the select dropdown in react.

[HttpGet("{ProductID}")]
public JsonResult GetProductInfo(int ProductID)
{
    var response = GetProductInfo(ProductID);

    return new JsonResult(response);
}

public string GetProductInfo(int Product_ID)
{
    SqlConnection objConnect = new SqlConnection(_connectionString);

    SqlCommand objCommand = new SqlCommand("usp_GetProdInfo", objConnect);

    objCommand.CommandType = CommandType.StoredProcedure;

    objCommand.Parameters.Add(new SqlParameter("@Product_ID", SqlDbType.Int, 4));

    objCommand.Parameters["@Product_ID"].Value = intProduct_ID;

    string json = string.Empty;

    List<object> objects = new List<object>();     

    objConnect.Open();

    SqlDataReader reader = objCommand.ExecuteReader();      
    while (reader.Read())
    {
        IDictionary<string, object> record = new Dictionary<string, object>();
        
        for (int i = 0; i < reader.FieldCount; i++)
        {
            record.Add(reader.GetName(i), reader[i]);
        }

        objects.Add(record);
    }

    json =JsonConvert.SerializeObject(objects);

    reader.Close();

    objConnect.Close();

    return json;
}
about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

you don't need to serialize data, Net can do it for you. And it is a very bad programming style to use objects instead of real classes. So return List instead of List

public ActionResult<List<Product>> GetProductInfo(int ProductID)
       {

         var response = GetProductInfoList(ProductID);

         if (response != null) return Ok(result)
         else retun BadRequest();

     }

     public List<Product> GetProductInfoList(int Product_ID)
     {
                List<Product> products = new List<Product>();    
                ...fix the code to get typed List<Product> from reader
                return products;
    }
about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!