Skip to content

Instantly share code, notes, and snippets.

@ducas
Created April 8, 2014 23:13
Show Gist options
  • Save ducas/10207222 to your computer and use it in GitHub Desktop.
Save ducas/10207222 to your computer and use it in GitHub Desktop.
ASP.Net Web API + JSend
using Newtonsoft.Json.Converters;
namespace Web.Core
{
public class CamelCaseStringEnumConverter : StringEnumConverter
{
public CamelCaseStringEnumConverter()
{
CamelCaseText = true;
}
}
}
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
namespace Web.Core
{
public class JSendMessageHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return base.SendAsync(request, cancellationToken)
.ContinueWith(t =>
{
if (request.Headers.Accept.All(a => a.MediaType != "application/json"))
return t.Result;
if (t.Result.Content != null && t.Result.Content.Headers.ContentType.MediaType != "application/json")
return t.Result;
object responseObject;
t.Result.TryGetContentValue(out responseObject);
if (t.Exception != null)
{
return request.CreateResponse(new JSendPayload
{
Status = JSendStatus.Error,
Message = t.Exception.Message,
Data = responseObject ?? t.Exception
});
}
if (t.IsCanceled)
{
return request.CreateResponse(new JSendPayload
{
Status = JSendStatus.Fail,
Message = "Operation Cancelled",
Data = responseObject ?? t.Exception
});
}
var errorContent = t.Result.Content as ObjectContent<HttpError>;
if (errorContent != null)
{
return request.CreateResponse(new JSendPayload
{
Status = JSendStatus.Error,
Message = t.Result.ReasonPhrase,
Code = (int)t.Result.StatusCode,
Data = responseObject
});
}
return request.CreateResponse(new JSendPayload
{
Status = JSendStatus.Success,
Data = responseObject
});
}, cancellationToken);
}
}
}
using Newtonsoft.Json;
namespace Web.Core
{
public class JSendPayload
{
[JsonConverter(typeof(CamelCaseStringEnumConverter))]
public JSendStatus Status { get; set; }
public object Data { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string Message { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public int? Code { get; set; }
}
}
namespace Web.Core
{
public enum JSendStatus
{
Success,
Fail,
Error
}
}
using System.Web.Http;
using Web.Core;
using Newtonsoft.Json.Serialization;
namespace Web
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.MessageHandlers.Add(new JSendMessageHandler());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment