从catch块向客户端发送格式化的错误消息

我使用以下代码从filter(ActionFilterAttribute)向客户端发送错误消息。

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

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

在这里我知道这是因为我正在使用StringContent()。 但是我们如何使用自定义Error对象编写? 比如,以下不起作用:

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

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

雅,我找到了正确的写作语法。 我们可以这样写:

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