我已将 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文章展示了如何实现自定义 IHttpControllerSelector
和 IHttpActionSelector
,它们使用典型的 ApiController
生成自定义 404 HttpResponseMessage
。
关于c# - Web API 中出现 404 Not Found 时返回自定义消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22439426/