Reputation: 1180
I have an API controller endpoint like:
public IHttpActionResult AddItem([FromUri] string name)
{
try
{
// call method
return this.Ok();
}
catch (MyException1 e)
{
return this.NotFound();
}
catch (MyException2 e)
{
return this.Content(HttpStatusCode.Conflict, e.Message);
}
}
This will return a string in the body like "here is your error msg"
, is there any way to return a JSON with 'Content'?
For example,
{
"message": "here is your error msg"
}
Upvotes: 7
Views: 12309
Reputation: 247641
Just construct the desired object model as an anonymous object and return that.
Currently you only return the raw exception message.
public IHttpActionResult AddItem([FromUri] string name) {
try {
// call service method
return this.Ok();
} catch (MyException1) {
return this.NotFound();
} catch (MyException2 e) {
var error = new { message = e.Message }; //<-- anonymous object
return this.Content(HttpStatusCode.Conflict, error);
}
}
Upvotes: 4
Reputation: 289
1) the easiest way: You can return directly whichever object you want, and it will be serialized as JSON. It can even be an anonymous class object created with new { }
2)
return new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = new ObjectContent(typeof(ErrorClass), errors, new JsonMediaTypeFormatter())
};
Upvotes: 0
Reputation: 789
In your case you need to return an object, where it should be like below, I didn't executed but please try
public class TestingMessage
{
[JsonProperty("message")]
public string message{ get; set; }
}
public IHttpActionResult AddItem([FromUri] string name)
{
TestingMessage errormsg=new TestingMessage();
try
{
// call service method
return this.Ok();
}
catch (MyException1)
{
return this.NotFound();
}
catch (MyException2 e)
{
string error=this.Content(HttpStatusCode.Conflict, e.Message);
errormsg.message=error;
return errormsg;
}
}
Upvotes: 2