0

Normally, I'd just do in my controller action:

return Content(System.Net.HttpStatusCode.InternalServerError, 
    new MyCustomObject("An error has occurred processing your request.", // Custom object, serialised to JSON automatically by the web api service
    ex.ToString()));`

However the Content method exists on the controller. The ExceptionHandler I made has this:

 public override void Handle(ExceptionHandlerContext context)
        {
            context.Result = ???;

The type of context.Result is IHttpActionResult, so what I need to do is create one and stick it in there. I can't find any constructors or similar that will allow me to create an IHttpActionResult outside of a controller. Is there an easy way?

NibblyPig
  • 51,118
  • 72
  • 200
  • 356
  • did you see this one: https://stackoverflow.com/questions/21758615/why-should-i-use-ihttpactionresult-instead-of-httpresponsemessage - Try and use ResponseMessage. – thewallrus Jan 06 '22 at 17:36

1 Answers1

0

I thing for custom responses you should probably implement your own http action result:

    public override void Handle(ExceptionHandlerContext context)
    {
        context.Result = new HttpContentResult(new { }, context.Request);
    }

    public class HttpContentResult : IHttpActionResult
    {
        private readonly object content;
        private readonly HttpRequestMessage requestMessage;

        public HttpContentResult(object content, HttpRequestMessage requestMessage)
        {
            this.content = content;
            this.requestMessage = requestMessage;
        }

        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            var httpContentResponse = new HttpResponseMessage(HttpStatusCode.BadRequest);
            var httpContent = new StringContent(content);
    
            //... [customize http contetnt properties]

            httpContentResponse.Content = httpContent;
            httpContentResponse.RequestMessage = this.requestMessage;

            //... [customize another http response properties]

            return Task.FromResult(httpContentResponse);
        }
    }
spzvtbg
  • 964
  • 5
  • 13