简体   繁体   中英

Returning JSON error message, IActionResult

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"
}

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);
    }
}

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;
    }
}

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())
    };
return Json(new {message = e.Message});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM