【问题标题】:.NET throw exception with JSON content type.NET 抛出 JSON 内容类型的异常
【发布时间】:2014-07-12 09:51:49
【问题描述】:

我正在开发一个使用 .NET MVC 4 框架的 Web API 项目。我的 API 专注于返回 JOSN 对象,除了当我想以 JSON 格式返回异常时,它工作得很好。

下面的代码是我用来尝试强制返回 JSON 的代码,但从该代码生成的响应是默认的 HTML 内容类型。我正在寻找一种使用“application/json”内容类型返回异常的方法。有什么建议吗?

public static void ThrowHttpException(HttpStatusCode code, string content)
{
    string message = JsonConvert.SerializeObject(new { message = content });
    var resp = new HttpResponseMessage(code)
    {
        Content = new StringContent(message),
        ReasonPhrase = null
    };
    throw new HttpResponseException(resp);
}

【问题讨论】:

  • throw new HttpResponseException(resp); 你发现这个异常了吗?
  • 您不应该首先返回HttpStatusCodeResult 吗?
  • 这东西看起来根本不像动作。它抛出异常而不是返回 ActionResult
  • 这是一个在 ApiController 中捕获到异常时调用的函数。
  • 你看过这个帖子吗:stackoverflow.com/questions/10732644/…?

标签: c# .net json asp.net-mvc-4


【解决方案1】:

您可能应该像这样创建操作:

public IHttpActionResult ThrowHttpException(HttpStatusCode code, string content)
{
    string message = JsonConvert.SerializeObject(new { message = content });
    var resp = new HttpResponseMessage(code)
    {
        Content = new StringContent(message),
        ReasonPhrase = null
    };
    return resp;
}

您应该从操作中返回响应对象,而不是引发异常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多