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

前端 未结 10 2104
情书的邮戳
情书的邮戳 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:11

    I was needing to create an IHttpActionResult instance in the body of an IExceptionHandler class, in order to set the ExceptionHandlerContext.Result property. However I also wanted to set a custom ReasonPhrase.

    I found that a ResponseMessageResult could wrap a HttpResponseMessage (which allows ReasonPhrase to be set easily).

    For Example:

    public class MyExceptionHandler : ExceptionHandler
    {
        public override void Handle(ExceptionHandlerContext context)
        {
            var ex = context.Exception as IRecordNotFoundException;
            if (ex != null)
            {
                context.Result = new ResponseMessageResult(new HttpResponseMessage(HttpStatusCode.NotFound) { ReasonPhrase = $"{ex.EntityName} not found" });
            }
        }
    }
    

提交回复
热议问题