返回JSON错误消息,IActionResult

hav*_*vij 5 c# json asp.net-web-api

我有一个API控制器端点,如:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

这将在正文中返回一个字符串"here is your error msg",有没有办法返回带有'Content'的JSON?

例如,

{
  "message": "here is your error msg"
}
Run Code Online (Sandbox Code Playgroud)

Nko*_*osi 4

只需将所需的对象模型构造为匿名对象并返回即可。

目前您仅返回原始异常消息。

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);
    }
}
Run Code Online (Sandbox Code Playgroud)