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

Sac*_*mar 6 c# asp.net-web-api

我使用以下代码从过滤器(ActionFilterAttribute)向客户端发送错误消息.

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

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

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

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

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

Sac*_*mar 8

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

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