0

My first API and my first JSON

I want to convert results from SQL Query

I want to put the results in a JSON so when users call the API they get a JSON text to consume.

I found this question here that help

How to use SqlCommand and SqlDataReader to return a Json result in C#

but when I try to apply the same in my code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Data;
using System.Data.SqlClient;
using System.Web.Mvc;

namespace CDAPIs.Controllers
{
    public class RepsSelect : ApiController
    {
        string gDBConn = "Data Source=Server;Database=DB1;User Id=user;Password=*******;";

        [Route("api/RepsSelect/{RepID}/{Tag}")]
        public string Get(string RepID, string Tag)
        {
            SqlConnection conn = new SqlConnection(gDBConn);
            SqlCommand cmd = new SqlCommand("RepsSelect", conn);
            cmd.CommandTimeout = 0;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter("@RepID", RepID));
            cmd.Parameters.Add(new SqlParameter("@Tag", ""));

            try
            {
                conn.Open();

                SqlDataReader rdr = cmd.ExecuteReader();

                var dt = new DataTable();
                dt.Load(rdr);
                List<DataRow> result = dt.AsEnumerable().ToList();
                rdr.Close();

                // Error is here
                return Json(result, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                var error = ex.Message;
                return View(error);
            }
        }
    }
}

I get these errors

CS1503 : Argument 2: cannot convert from "System.Web.Mvc.JsonRequestBehavior" to "Newtonsoft.Json.JsonSerializedSettings"

enter image description here

I tried using Newtonsoft.Json instead of System.Web.Mvc but I got this error enter image description here

3
  • Never paste the error messages as images. If you fix it I'll reverse the vote. Commented May 10, 2021 at 5:28
  • @JeremyThompson the error message itself is already above the image!! Commented May 10, 2021 at 5:54
  • The second image is what I was talking about Commented May 10, 2021 at 7:22

2 Answers 2

2

When working with APIs - we want to work with the http response protocol (best practice).

Try changing this

public HttpResponseMessage Get(string RepID, string Tag)

and then

return Request.CreateResponse(HttpStatusCode.OK, result, Configuration.Formatters.JsonFormatter);

In the catch block you will want to return

Request.CreateErrorResponse(HttpStatusCode.NotFound, "Data Not Found");

Kia Kaha asmgx,

Mike Smith

Sign up to request clarification or add additional context in comments.

2 Comments

can you validate your claim of best practice in any way?
Good question. Generally from the API you want to handle error responses as well as your success responses with the appropriate HTTP result from the API - such as (200 Ok), (404 Not Found) etc. You could return a string/json as the return type but I personally would avoid that as I prefer to inform the client of the correct response type. Cheers
2

you need to change

    [Route("api/RepsSelect/{RepID}/{Tag}")]
    public string Get(string RepID, string Tag)

to

    [Route("api/RepsSelect/{RepID}/{Tag}")]
    public JsonResult Get(string RepID, string Tag)

1 Comment

why? why do this as oppose to serializing in the method and not modifying the return method signature? i.e. why is it necessary to make that change?

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.