c# - Web API 中出现 404 Not Found 时返回自定义消息

标签 c# json asp.net-web-api

我已将 config.Formatters.Remove(config.Formatters.XmlFormatter); 添加到 ASP.NET Web API 项目中 WebApiConfig.cs 的 Register 方法。当发生 404 Not Found 异常时,这可以很好地返回 JSON。我收到如下消息:

{"Message":"No HTTP resource was found that matches the request URI 'http://localhost:2034/api/dfdf'.","MessageDetail":"No type was found that matches the controller named 'dfdf'."}

是否可以覆盖此消息以返回自定义消息?如果是这样,它是如何完成的?我正在使用 Web API 2。

最佳答案

这看起来很简单,但有很多地方 ASP.Net 会自动创建 404(而不是您的 Controller 手动返回 404 响应)。

  • 没有匹配的路线。
  • 路线匹配,但在路线上未找到 {controller}。
  • 未找到名称为{controller} 的类型。
  • 由于没有以请求 HTTP 方法动词开头的操作方法,或者没有找到具有 IActionHttpMethodProviderRoute 实现属性的操作方法,或者没有找到具有 {action} 名称的方法,或者没有找到具有匹配 {action 的方法,因此在所选 Controller 中找不到匹配的操作方法} 找到了名字。

This文章展示了如何实现自定义 IHttpControllerSelectorIHttpActionSelector,它们使用典型的 ApiController 生成自定义 404 HttpResponseMessage

关于c# - Web API 中出现 404 Not Found 时返回自定义消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22439426/

相关文章:

c# - ASP.Net C# MVC EditorFor Template 未从主 Razor View 调用

c# - 使用JSON.net解析json字符串

javascript - 重构 JSON 以与 Firebase 实时数据库一起使用

c# - 当用户没有将完整的 json 传递给 .NET Web API 时怎么办?

c# - 通过安全和性能感知将整个数据表存储在 Viewstate 中是否合适

c# - 在不同文档中查找相似段落

c# - 如何在C#中从mysql结果中读取某些数据

php - 使用 PHP 在 Mysql 中数组到字符串错误

asp.net-web-api - Web API/MVC 6 中的安全 JSON Web token

android - asp.net mvc中的Web应用程序与移动应用程序通信