7

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"
}
havij
  • 1,030
  • 14
  • 29

4 Answers4

4

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);
    }
}
Nkosi
  • 235,767
  • 35
  • 427
  • 472
2

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;
    }
}
PrathapG
  • 751
  • 1
  • 7
  • 21
0

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())
    };
Mohammad Hatami
  • 299
  • 3
  • 9
0
return Json(new {message = e.Message});
frogcoder
  • 963
  • 1
  • 7
  • 17