C# .NET抛出JSON内容类型异常
我正在从事一个使用.NETMVC4框架的WebAPI项目。我的API专注于返回JOSN对象,除了以JSON格式返回异常外,它工作得非常完美 下面的代码是我用来尝试和强制返回JSON的代码,但是从这段代码生成的响应是默认的HTML内容类型。我正在寻找一种使用“application/json”内容类型返回异常的方法。有什么建议吗C# .NET抛出JSON内容类型异常,c#,.net,json,asp.net-mvc-4,C#,.net,Json,Asp.net Mvc 4,我正在从事一个使用.NETMVC4框架的WebAPI项目。我的API专注于返回JOSN对象,除了以JSON格式返回异常外,它工作得非常完美 下面的代码是我用来尝试和强制返回JSON的代码,但是从这段代码生成的响应是默认的HTML内容类型。我正在寻找一种使用“application/json”内容类型返回异常的方法。有什么建议吗 public static void ThrowHttpException(HttpStatusCode code, string content) { stri
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;
}
您应该从操作返回响应对象,而不是抛出异常。
抛出新的HttpResponseException(resp)代码>您是否捕获到此异常?您不应该首先返回一个吗?这看起来根本不像操作。它抛出异常而不是返回ActionResult这是一个在ApicController中捕获异常时调用的函数?