Skip to content

Instantly share code, notes, and snippets.

@ajile-in
Last active December 29, 2015 07:49
Show Gist options
  • Save ajile-in/7638562 to your computer and use it in GitHub Desktop.
Save ajile-in/7638562 to your computer and use it in GitHub Desktop.
Custom action implementation using IHttpActionResult
public class CustomActionResult : IHttpActionResult
{
private HttpStatusCode _statusCode { get; set; }
private string _message { get; set; }
private Exception _exception { get; set; }
public CustomActionResult(HttpStatusCode statusCode, string errorMessage) : this(statusCode, errorMessage, null)
{}
public CustomActionResult(HttpStatusCode statusCode, string errorMessage, Exception exception)
{
_statusCode = statusCode;
_message = errorMessage;
_exception = exception;
}
public Task<HttpResponseMessage> ExecuteAsync(System.Threading.CancellationToken cancellationToken)
{
HttpResponseMessage response = new HttpResponseMessage(_statusCode);
StringBuilder stringBldr = new StringBuilder();
stringBldr.Append(_message);
if (_exception != null)
{
stringBldr.Append(_exception.ToString());
}
response.Content = new StringContent(stringBldr.ToString());
return Task.FromResult(response);
}
}
public class CustomNotFoundActionResult : CustomActionResult
{
public CustomNotFoundActionResult(string errorMessage)
: this(errorMessage, null)
{}
public CustomNotFoundActionResult(string errorMessage, Exception exception)
: base(HttpStatusCode.NotFound, errorMessage, exception)
{}
}
public class GenericApiController : ApiController
{
private NamedLogger _logger = null;
protected NamedLogger Log
{
get
{
if (_logger == null)
{
_logger = new NamedLogger(GetType().Name);
}
return _logger;
}
}
public virtual IHttpActionResult CustomNotFoundResult(string errorMessage)
{
return this.CustomNotFoundResult(errorMessage, null);
}
public virtual IHttpActionResult CustomNotFoundResult(string errorMessage, Exception exception)
{
CustomNotFoundActionResult result = new CustomNotFoundActionResult(errorMessage, exception);
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment