'how to convert string response to JSON response
Here if the response is success I want to return JSON responseStr with status code System.Net.HttpStatusCode.Accepted. But using this code I am able to return string. But I want to return Json response.
public async Task<IActionResult> Receipt()
{
var response = await api.Get(string.Format(url));
var responseStr = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
return StatusCode((int)System.Net.HttpStatusCode.Accepted, responseStr);
}
else
{
_logger.LogError(responseStr);
return BadRequest(responseStr);
}
}
Solution 1:[1]
Ordinarily a 202 / Accepted response wouldn't contain a body in the response.
But you can achieve this by either of the following:
return Accepted(responseStr);
Note that this will return the responseStr field as a string - because it is a string.
If you want to return it as a json object - you could deserialise it first and return the object in the same manner:
var asObject = JsonConvert.DeserializeObject<Type>(responseStr);
return Accepted (asObject);
Also, you should move the ReadAsStringAsync call to inside the if (Successful) {} block.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | David McEleney |
