'How to return a object in HttpResponseMessage in Web api mvc?
In one of my Get request, I want to return an HttpResponseMessage with some content. Currently I have it working as follows:
// GET api/Account/5
[HttpGet]
[ActionName("GetAccount")]
public HttpResponseMessage GetAccount(int id)
{
Account value;
try
{
var myque = from x in db.Accounts where x.idUser==id select x;
value= myque.FirstOrDefault();
}
catch (Exception)
{
return new HttpResponseMessage { Content = new StringContent("[{\"Success\":\"Fail\"},{\"Message\":\"Login Fail\"}]", System.Text.Encoding.UTF8, "application/json") };
}
return new HttpResponseMessage { Content = new StringContent("[{\"Success\":\"Success\"},{\"Message\":\"Login successfully\"}],{\"Data\":"+value+"}", System.Text.Encoding.UTF8, "application/json") };
}
I want to add value to HttpResponseMessage. Value will return a json normal.
[
{
"Success": "Success"
},
{
"Message": "successfully"
}
Value will display at here
]
Solution 1:[1]
Since you are using [ActionName("GetAccount")]... you should use IActionResult as the return type.
Otherwise if you want to use HttpResponseMessage, use -
[Route("api/GetAccount")]
Also, you can construct the output result like
return new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = data };
Solution 2:[2]
Use Jobject to return
return new JObject(<your dynamic object here>);
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 | |
| Solution 2 |
