Skip to content

Instantly share code, notes, and snippets.

@dcomartin
Created January 18, 2018 00:58
Show Gist options
  • Save dcomartin/92d3149e554c9778944b9e07150d8a2c to your computer and use it in GitHub Desktop.
Save dcomartin/92d3149e554c9778944b9e07150d8a2c to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.Net.Http.Headers;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Hangman.Api.Siren.Formatters
{
public class SirenOutputFormatter : TextOutputFormatter
{
private static readonly JsonSerializerSettings DefaultJsonSerializerSettings
= new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
NullValueHandling = NullValueHandling.Ignore,
};
private static readonly Encoding DefaultEncoding = Encoding.UTF8;
private readonly Dictionary<Type, object> _templates;
private readonly JsonSerializerSettings _jsonSerializerSettings;
public SirenOutputFormatter(Dictionary<Type, object> templates)
: this(templates, DefaultJsonSerializerSettings, DefaultEncoding)
{
}
public SirenOutputFormatter(Dictionary<Type, object> templates, JsonSerializerSettings settings)
: this(templates, settings, DefaultEncoding)
{
}
public SirenOutputFormatter(Dictionary<Type, object> templates, Encoding encoding)
: this(templates, DefaultJsonSerializerSettings, encoding)
{
}
public SirenOutputFormatter(Dictionary<Type, object> templates, JsonSerializerSettings settings, Encoding encoding)
{
_templates = templates;
_jsonSerializerSettings = settings;
SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/vnd.siren+json"));
SupportedEncodings.Add(encoding);
}
protected override bool CanWriteType(Type type)
{
return _templates.ContainsKey(type);
}
public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
{
var template = _templates[context.ObjectType];
var builder = template.GetType()
.GetMethod("ToRepresentation")
.Invoke(template, new [] {context.Object});
var entity = builder.GetType().GetMethod("Build").Invoke(builder, new object[0]);
return context.HttpContext.Response.WriteAsync(
JsonConvert.SerializeObject(entity, _jsonSerializerSettings),
selectedEncoding,
context.HttpContext.RequestAborted);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment