Last active
December 29, 2015 07:49
-
-
Save ajile-in/7638562 to your computer and use it in GitHub Desktop.
Custom action implementation using IHttpActionResult
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class CustomNotFoundActionResult : CustomActionResult | |
{ | |
public CustomNotFoundActionResult(string errorMessage) | |
: this(errorMessage, null) | |
{} | |
public CustomNotFoundActionResult(string errorMessage, Exception exception) | |
: base(HttpStatusCode.NotFound, errorMessage, exception) | |
{} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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