Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid JSON deserialize / serialize in Web API?

I have the following code in a Web API controller in ASP.NET 2.0:

[HttpGet]
[Route("{controllerName}/{nodeId}/ConfigurationValues")]
public async Task<IActionResult> GetConfigurationValues(string controllerName, byte nodeId, string code)
{
    string payload = ...

    HttpResponseMessage response = await deviceControllerRepository.ExecuteMethodAsync(controllerName, "GetNodeConfigurationValues", payload);

    string responseJson = await response.Content.ReadAsStringAsync();
    var configurationValues = JsonConvert.DeserializeObject<List<ConfigurationValue>>(responseJson);

    return Ok(configurationValues);
}

How can I avoid having to de-serialize the responseJson into a .NET object before returning it as it already is in the correct JSON format?

I tried to change the method into returning HttpResponseMessage, but that resulted in incorrect JSON being passed back to the caller.

like image 441
OlavT Avatar asked Dec 21 '25 10:12

OlavT


1 Answers

ControllerBase class has a Content() method for this purpose. Make sure you set correct Content-Type header in output packet:

return Content(responseJson, "application/json");
like image 100
CodeFuller Avatar answered Dec 24 '25 10:12

CodeFuller