Skip to content

Instantly share code, notes, and snippets.

@sixeyed
Created April 8, 2014 12:45
Show Gist options
  • Save sixeyed/10118609 to your computer and use it in GitHub Desktop.
Save sixeyed/10118609 to your computer and use it in GitHub Desktop.
Wrapping WebApi IHttpActionResult to expose the response message to controllers
using SampleApi.Results;
using System;
using System.Net.Http;
using System.Web.Http;
namespace SampleApi
{
public static class IHttpActionResultExtensions
{
public static IHttpActionResult With(this IHttpActionResult inner, string responsePhrase = null, Action<HttpResponseMessage> responseAction = null)
{
return new WrappedHttpActionResult(inner, responsePhrase, responseAction);
}
public static IHttpActionResult With(this IHttpActionResult inner, Action<HttpResponseMessage> responseAction)
{
return new WrappedHttpActionResult(inner, responseAction);
}
}
}
using System.Net.Http.Headers;
using System.Web.Http;
namespace SampleApi.Controllers
{
public class ValuesController : ApiController
{
public IHttpActionResult Get(int id)
{
//404 with custom reason phrase
if (id < 1)
return NotFound().With("Could not find object");
//200 with ETag
var response = new { id = id, name = "xyz" };
return Ok(response).With(x => x.Headers.ETag = new EntityTagHeaderValue(@"""etag"""));
}
}
}
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
namespace SampleApi.Results
{
public class WrappedHttpActionResult : IHttpActionResult
{
private IHttpActionResult _innerResult;
private string _responsePhrase;
private Action<HttpResponseMessage> _responseAction;
public WrappedHttpActionResult(IHttpActionResult inner, Action<HttpResponseMessage> responseAction)
: this(inner, null, responseAction)
{
}
public WrappedHttpActionResult(IHttpActionResult inner, string responsePhrase, Action<HttpResponseMessage> responseAction = null)
{
_innerResult = inner;
_responsePhrase = responsePhrase;
_responseAction = responseAction;
}
public async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = await _innerResult.ExecuteAsync(cancellationToken);
if (!string.IsNullOrWhiteSpace(_responsePhrase))
{
response.ReasonPhrase = _responsePhrase;
}
if (_responseAction != null)
{
_responseAction(response);
}
return response;
}
}
}
@adrynov
Copy link

adrynov commented Oct 15, 2014

Useful, thank you

@brunchey
Copy link

Second thanks

@furnlound
Copy link

Cheers!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment