Skip to content

Instantly share code, notes, and snippets.

@seangwright
Created April 23, 2016 18:12
Show Gist options
  • Save seangwright/26ba55cf0ad8cfeebaaa63171c2bdb71 to your computer and use it in GitHub Desktop.
Save seangwright/26ba55cf0ad8cfeebaaa63171c2bdb71 to your computer and use it in GitHub Desktop.
ErrorResult.cs
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
namespace WiredViews.WIR03.Web.Api.Results
{
public class ErrorResult : IHttpActionResult
{
private static JsonMediaTypeFormatter formatter;
private static JsonSerializerSettings settings;
private readonly object _errorMessage;
private readonly HttpRequestMessage _requestMessage;
private readonly HttpStatusCode _statusCode;
static ErrorResult()
{
formatter = new JsonMediaTypeFormatter();
settings = formatter.SerializerSettings;
settings.Formatting = Formatting.Indented;
// UTC Date serialization configuration
settings.DateFormatHandling = DateFormatHandling.IsoDateFormat;
settings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
settings.DateFormatString = "yyyy-MM-ddTHH:mm:ss.fffK";
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
public ErrorResult(HttpRequestMessage requestMessage, HttpStatusCode statusCode, string errorMessage)
{
_requestMessage = requestMessage;
_statusCode = statusCode;
_errorMessage = new { Message = errorMessage };
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = _requestMessage.CreateResponse(_statusCode, _errorMessage, formatter, new MediaTypeHeaderValue("application/json"));
return Task.FromResult(response);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment