簡體   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