Search code examples
jsonasp.net-corehttpresponsemessage

Convert an object to Json in ASP.net Core


I am trying to convert and object "Persona" to a json string in .net Framework 4 and i need help.

I have tried this (using System.Text.Json)

public HttpResponseMessage Get(int id){
  HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
    Personas persona = context.tPersonas.FirstOrDefault(p => p.idPersona == id);
    if (persona != null){
      var jsonData = JsonSerializer.Serialize(persona);
      response.Content = new StringContent(jsonData);
      response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
      return response;
    }
  else
    return response = new HttpResponseMessage(HttpStatusCode.BadRequest);            
} 

And this (using Newtonsoft.Json);

 public HttpResponseMessage Get(int id)
        {
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
            Personas persona = context.tPersonas.FirstOrDefault(p => p.idPersona == id);
            if (persona != null)
            {
                response.Content = new StringContent(JsonConvert.SerializeObject(persona));
                response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                return response;
            }
            else
                return response = new HttpResponseMessage(HttpStatusCode.BadRequest);            
        }

When debugging, "persona" has data and "Serialize" shows null.

I tried also "Request.CreateResponse" but it is not recognized as a valid code for some weird reason.

Which step am I Skipping?


Solution

  • If you want to use HttpResponseMessage to return information in asp.core mvc, you need to complete the following steps.

    • Install Microsoft.AspNetCore.Mvc.WebApiCompatShim package for your project.
    • Add services.AddMvc().AddWebApiConventions(); to ConfigureServices in the starup.cs file.

    Here is the code:

        public HttpResponseMessage Get(int id)
        {
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
            Personas persona = _context.tPersonas.FirstOrDefault(p => p.idPersona == id);
            if (persona != null)
            {
                response.Content = new StringContent(JsonConvert.SerializeObject(persona));
                response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                return response;
            }
            else
            {
                response = new HttpResponseMessage(HttpStatusCode.BadRequest);
                response.Content = new StringContent("error message");
                return response;
            }
    
        } 
    

    You can also refer to this.

    Here is the debug process from postman:

    enter image description here