2012-06-27 82 views
6

我使用以下代码从过滤器(ActionFilterAttribute)向客户端发送错误消息。从catch块发送格式错误消息给客户端

catch (Exception) 
{ 
    var response = context.Request.CreateResponse(httpStatusCode.Unauthorized); 
    response.Content = new StringContent("User with api key is not valid"); 
    context.Response = response; 
} 

但问题是它只发送纯文本。我想将它作为当前格式化程序的格式发送。就像json或xml一样。

在这里我知道这是因为我使用StringContent()。但是我们如何编写使用自定义错误对象? 像,下面不工作之一:

response.Content = new Error({Message = "User with api key is not valid"}); 

我们如何编写代码呢?提前致谢。

回答

8

雅,我发现写作的正确语法。我们可以这样写:

catch (Exception) 
{ 
    var response = context.Request.CreateResponse(HttpStatusCode.NotFound, 
         new Error { Message = "User with api key is not valid"}); 
    context.Response = response; 
} 
+0

如何在MVC 3中做到这一点? –

相关问题