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

前端 未结 10 2108
情书的邮戳
情书的邮戳 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 08:05

    If you inherit from the base NegotitatedContentResult, as mentioned, and you don't need to transform your content (e.g. you just want to return a string), then you don't need to override the ExecuteAsync method.

    All you need to do is provide an appropriate type definition and a constructor that tells the base which HTTP Status Code to return. Everything else just works.

    Here are examples for both NotFound and InternalServerError:

    public class NotFoundNegotiatedContentResult : NegotiatedContentResult
    {
        public NotFoundNegotiatedContentResult(string content, ApiController controller)
            : base(HttpStatusCode.NotFound, content, controller) { }
    }
    
    public class InternalServerErrorNegotiatedContentResult : NegotiatedContentResult
    {
        public InternalServerErrorNegotiatedContentResult(string content, ApiController controller)
            : base(HttpStatusCode.InternalServerError, content, controller) { }
    }
    

    And then you can create corresponding extension methods for ApiController (or do it in a base class if you have one):

    public static NotFoundNegotiatedContentResult NotFound(this ApiController controller, string message)
    {
        return new NotFoundNegotiatedContentResult(message, controller);
    }
    
    public static InternalServerErrorNegotiatedContentResult InternalServerError(this ApiController controller, string message)
    {
        return new InternalServerErrorNegotiatedContentResult(message, controller);
    }
    

    And then they work just like the built-in methods. You can either call the existing NotFound() or you can call your new custom NotFound(myErrorMessage).

    And of course, you can get rid of the "hard-coded" string types in the custom type definitions and leave it generic if you want, but then you may have to worry about the ExecuteAsync stuff, depending on what your actually is.

    You can look over the source code for NegotiatedContentResult to see all it does. There isn't much to it.

提交回复
热议问题