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