c# - 返回 JSON 错误消息,IActionResult

标签 c# json asp.net-web-api

我有一个 API Controller 端点,例如:

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

这将在正文中返回一个字符串,如 “这是你的错误信息”,有什么方法可以返回带有“Content”的 JSON 吗?

例如,

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

最佳答案

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

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

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

关于c# - 返回 JSON 错误消息,IActionResult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53625036/

相关文章:

java - 应为 BEGIN_OBJECT,但为 STRING - 没有键的 json

c# - 对依赖于 User.Identity 对象的 ASP.Net Web API Controller 进行单元测试

c# - 将对象数组传递给 webapi

c# - 如何将 View 模型从 Controller 传递给 Web api 方法

c# - 随机字符串 c#

c# - 不能隐式转换 bool 类型?

c# - new object[] {} 与 Array.Empty<object>()

javascript - 在android中转换特定类型的json字符串

c# - 将项目添加到嵌套列表中的嵌套列表的 View

java - Java 中的多个数组和对象 JSON