Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.