How do I return NotFound() IHttpActionResult with an error message or exception?

前端 未结 10 2107
情书的邮戳
情书的邮戳 2020-12-02 07:18

I am returning a NotFound IHttpActionResult, when something is not found in my WebApi GET action. Along with this response, I want to send a custom message and/

10条回答
  •  孤城傲影
    2020-12-02 07:51

    Answers here are missing a little developer story problem. The ApiController class is still exposing a NotFound() method that developers may use. This would cause some 404 response to contain a uncontrolled result body.

    I present here a few parts of code "better ApiController NotFound method" that will provide a less error-prone method that does not require developers to know "the better way of sending a 404".

    • create a class inheriting from ApiController called ApiController
      • I use this technique to prevent developers from using the original class
    • override its NotFound method to let devs use the first available api
    • if you want to discourage this, mark this as [Obsolete("Use overload instead")]
    • add an extra protected NotFoundResult NotFound(string message) that you want to encourage
    • problem: the result does not support responding with a body. solution: inherit and use NegotiatedContentResult. see attached better NotFoundResult class.

提交回复
热议问题