Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# .NET抛出JSON内容类型异常_C#_.net_Json_Asp.net Mvc 4 - Fatal编程技术网

C# .NET抛出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

我正在从事一个使用.NETMVC4框架的WebAPI项目。我的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;
}

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

抛出新的HttpResponseException(resp)您是否捕获到此异常?您不应该首先返回一个吗?这看起来根本不像操作。它抛出异常而不是返回ActionResult这是一个在ApicController中捕获异常时调用的函数?