. net抛出JSON内容类型的异常

本文关键字:类型 异常 抛出 JSON net | 更新日期: 2023-09-27 18:12:40

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

下面的代码是我用来尝试强制JSON返回的,但是从该代码生成的响应是默认的HTML内容类型。我正在寻找一种方法来返回使用"应用程序/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);
}

. net抛出JSON内容类型的异常

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

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

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

相关文章: