返回JSON错误消息,IActionResult

时间:2018-12-05 04:07:42

标签: 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);
    }
}

这将在正文中返回一个类似于"here is your error msg"的字符串,是否有任何方法可以返回带有“ Content”的JSON?

例如,

{
  "message": "here is your error msg"
}

4 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分:1)

在您的情况下,您需要返回一个对象,该对象应如下所示,但我没有执行,但请尝试

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

答案 2 :(得分:0)

1)最简单的方法:您可以直接返回所需的任何对象,并将其序列化为JSON。它甚至可以是使用新{}

创建的匿名类对象。

2)

return new HttpResponseMessage(HttpStatusCode.BadRequest)
    {
        Content = new ObjectContent(typeof(ErrorClass), errors, new JsonMediaTypeFormatter())
    };

答案 3 :(得分:0)

return Json(new {message = e.Message});