简体   繁体   English

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

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

i am using the following code to send out error message to client from a filter(ActionFilterAttribute). 我使用以下代码从过滤器(ActionFilterAttribute)向客户端发送错误消息。

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

But problem is that it sends out in plain text only. 但问题是它只以纯文本形式发出。 I wanted to send it as format of current formatter. 我想把它作为当前格式化程序的格式发送。 Like in form of json or xml. 像json或xml的形式。

Here i know that this is because i am using StringContent(). 在这里我知道这是因为我正在使用StringContent()。 But how can we write using custom Error object? 但是我们如何使用自定义Error对象编写? like, the following is not working either: 比如,以下不起作用:

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

How do we write code for this? 我们如何为此编写代码? Thanks in advance. 提前致谢。

Ya, i found the correct syntax of writing. 雅,我找到了正确的写作语法。 We can write like: 我们可以这样写:

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