3

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.

5
  • What does deviceControllerRepository do? and why can't you make it return object instead of HttpResponseMessage? Commented Nov 12, 2017 at 14:35
  • Could you write that string to the response and return Ok() without providing it the argument as you do now. Commented Nov 12, 2017 at 14:35
  • @Rob, Ok() will send 'text/plain' in Content-Type header. Commented Nov 12, 2017 at 14:43
  • Im not near a PC now but there should be Json method that controller exposes. I know that method takes an object but you can try passing it a string as well. Commented Nov 12, 2017 at 14:53
  • If you use just return Json("{\"Value\": 5}") you'll get following in body of output packet: "{\"Value\": 5}". It's not a valid json becaus of embracing quotes. Commented Nov 12, 2017 at 14:59

2 Answers 2

3

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");
Sign up to request clarification or add additional context in comments.

Comments

0

You can return ContentResult instead of Ok() for avoiding unnecessary serialization:

return new ContentResult
    {
        Content = responseJson,
        ContentType = "application/json",
        StatusCode = 200
    };

1 Comment

There is a Content() method that will construct ContentResult for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.