c# - .NET 抛出 JSON 内容类型的异常

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

我正在开发一个使用 .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);
}

最佳答案

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

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

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

关于c# - .NET 抛出 JSON 内容类型的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24711738/

相关文章:

c# - SortedDictionary<TKey, TValue> : check if contents equal to another SortedDictionary?

c# - JSON Deserialization Despair(无法反序列化嵌套类型)

c# - 针对匿名对象的 System.Text.Json 序列化

c# - checkin 对象数组

c# - 使用 jQuery 将表单数据发布到 MVC4 Controller 操作方法时出现问题

java - Jquery 与 Servlet 获取数据库 JSON 数组对象

c# - 如何使用反射对 Dispose() 进行单元测试?

c# - 使用托管代码包装器从 64 位托管代码调用 32 位非托管代码的最佳方式

.net - 如何将 C++ 字符串转换为 .NET 字符串^?

javascript - JSON验证