Click here to Skip to main content
16,022,296 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello,
This is my model:
public class EncabezadoModel
  {
      public string NúmeroEPS { get; set; }
      public string Nombres { get; set; }
      public string Identificación { get; set; }
      public string Teléfono { get; set; }
      public string Email { get; set; }
      public decimal TotalPaquetes { get; set; }
      public string Estatus { get; set; }


  }

  public class Paquete
  {
      public string Guia { get; set; }
      public string DescripcióndeMercancia { get; set; }
      public decimal TotalLibra { get; set; }
      public DateTime Fecha { get; set; }
      public string Servicio { get; set; }
      public string Estatus { get; set; }

  }

  public class ValidacionModel
  {
      public EncabezadoModel Encabezado { get; set; }
      public List<Paquete> detalles { get; set; }
  }


This is my controller (very simple)
public class PaqueteController : ApiController
    {  
        public object Get(string id)
        {
            String jsonStr = UsuarioPaquete.Listar(id);
            jsonStr = jsonStr.Replace("\r\n", "").Replace(@"\", "");
            dynamic jsonObject = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonStr);
            return jsonObject; } 

        
    }


This is the class to create the JSON output
using (SqlConnection oCon = new SqlConnection(Conexion.pathConexion))
        {
            ValidacionModel jsonObject = new ValidacionModel();
            jsonObject.detalles = new List<Paquete>();
            SqlCommand cmd = new SqlCommand("sp_listar", oCon);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@id", id.ToUpper());
            try
            {
                oCon.Open();
                using (SqlDataReader dr = cmd.ExecuteReader())
                {

                       //Here a i have some code to add the Encabezado

                        jsonObject.detalles.Add(new Paquete()
                        {
                            Guia= dr["Guia"].ToString(),
                            DescripcióndeMercancia = dr["DescripciondeMercancia"].ToString(),
                            TotalLibra = Convert.ToDecimal(dr["TotalLibra"].ToString()),
                            Fecha = Convert.ToDateTime(dr["Fecha"].ToString()),
                            Servicio = dr["servicio"].ToString(),
                            Estatus = dr["EstatusNombre"].ToString(),
                        });
                string json = JsonConvert.SerializeObject(jsonObject);

                return json;


The problem is: If i use postman the output look like a JSON, you can see it as a json file. That is correct, but when i use IIS in the explorer i have the format (look like a json) but it is a text string, so in order to see it you have to check the: FORMAT STRING in the explorer.

I have this line in the global.asax:
protected void Application_Start()
      {
          GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
          GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
          GlobalConfiguration.Configure(WebApiConfig.Register);
      }
      public static void Register(HttpConfiguration config)
      {
          config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings()
          {
              Formatting = Formatting.Indented,
              TypeNameHandling = TypeNameHandling.Auto,
              ContractResolver = new CamelCasePropertyNamesContractResolver(),
              NullValueHandling = NullValueHandling.Ignore,
              ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore

          };


But nothing happen

Any help?
thanks in advance

What I have tried:

I had use newthon formatted,
I had insert code to format the explorer string :
Posted

1 solution

It looks like your API returns JSON as plain text when you access it through a browser, but it shows up correctly in Postman. This issue often happens because the browser or server isn't set up to handle JSON responses properly.

Here’s how to fix it:

Update Your Controller
Change the Return Type: Instead of returning object, use IHttpActionResult. This helps make sure the response is handled correctly.

Return JSON Directly: Use Ok() to return your JSON response properly.

Here’s an updated version of your controller code:

public class PaqueteController : ApiController
{
    public IHttpActionResult Get(string id)
    {
        try
        {
            string jsonStr = UsuarioPaquete.Listar(id);
            jsonStr = jsonStr.Replace("\r\n", "").Replace(@"\", "");
            var jsonObject = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonStr);

            // Return the JSON object with the correct content type
            return Ok(jsonObject);
        }
        catch (Exception ex)
        {
            return InternalServerError(ex);
        }
    }
}

Check Global Configuration
In your Global.asax file, make sure you have these settings:

protected void Application_Start()
{
    GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
    GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Formatting = Formatting.Indented;
    GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
    GlobalConfiguration.Configure(WebApiConfig.Register);
}

Check IIS Settings
Make sure IIS isn’t changing how your content is handled:

Content-Type Header: Ensure the response is being sent with Content-Type: application/json. The Ok() method should handle this, but double-check.

Static Files: Verify that IIS isn’t treating your API response like a static file or applying any rules that might interfere.

Test Your API
After making these changes, test your API again:

In Postman: It should show the JSON correctly.
In a Browser: Check if it displays as JSON instead of plain text.
Also, use the browser’s Developer Tools to check if the Content-Type header is set to application/json. This can help you see if the response is being handled correctly.

These steps should help ensure your API returns JSON properly both in Postman and in a browser.
 
Share this answer
 
Comments
Dave Kreskowiak 22-Jul-24 9:44am    
Answers from ChatGPT are not allowed.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900