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 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.