繁体   English   中英

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

[英]Sending formatted error message to client from catch block

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

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()。 但是我们如何使用自定义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; 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM