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?
If you want to use HttpResponseMessage
to return information in ASP.NET Core MVC, you need to complete the following steps:
Microsoft.AspNetCore.Mvc.WebApiCompatShim
package for your projectservices.AddMvc().AddWebApiConventions();
to ConfigureServices in the startup.cs
fileHere 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: