【问题标题】:Change Error response in web API更改 Web API 中的错误响应
【发布时间】:2016-05-09 08:24:02
【问题描述】:

我在我的 Web Api 应用程序中使用基于令牌的身份验证。 在登录请求中,如果用户输入了错误的凭据,则返回此格式的响应错误。

在GrantResourceOwnerCredentials方法中

if (user == null)
    {
      context.SetError("The email or password is incorrect.");
      return;
    }

返回响应为

 {
      "error": "InvalidLogin",
      "error_description": "The email or password is incorrect."
    }

在我的应用程序中,所有错误响应都以这种格式返回

{
  "message": "Some Internal server error occurred."
}

那么如何更改web api的错误响应 到

    {
      "message": "The email or password is incorrect."
    }

【问题讨论】:

  • 什么是“我的应用程序”?它是否在消耗您的 Web Api 应用程序?
  • 可以发一下web api应用代码
  • @KrishnaChaithanyaMuthyala:我创建了一个 webAPI 应用程序。
  • @PranavPatel:查看更新后的问题
  • 那么,您想标准化来自所有 API 的所有响应吗?是这样吗?你觉得标准化有什么问题吗?或者,您想知道最佳做法是什么?

标签: c# asp.net-mvc asp.net-web-api


【解决方案1】:

编辑:试试这个

string jsonString = "{\"message\": \"The email or password is incorrect.\"}";
context.SetError(new string(' ',jsonString.Length-12)); 
context.Response.StatusCode = 400;
context.Response.Write(jsonString);

【讨论】:

  • 不会回复{ "error": "message", "error_description": "The email or password is incorrect." }
  • 为什么是jsonString.Length-12?
  • 删除部分\"message\":
  • 我怎样才能返回"{\"message\": \"The email or password is incorrect.\",\"error_code\": \"400.\"}"; 你也可以请你删除\"message\":
猜你喜欢
  • 2011-09-12
  • 1970-01-01
  • 1970-01-01
  • 2017-06-16
  • 2023-03-27
  • 2019-06-25
  • 2015-10-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多