41 lines
1.6 KiB
C#
41 lines
1.6 KiB
C#
namespace ALttPRandomizer.Serialization {
|
|
using System;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.AspNetCore.Mvc.Formatters;
|
|
using Microsoft.Extensions.Logging;
|
|
using Microsoft.Net.Http.Headers;
|
|
using YamlDotNet.Serialization;
|
|
|
|
public class YamlInputFormatter : TextInputFormatter {
|
|
private IDeserializer Deserializer { get; }
|
|
private ILogger<YamlInputFormatter> Logger { get; }
|
|
|
|
public YamlInputFormatter(IDeserializer deserializer, ILogger<YamlInputFormatter> logger) {
|
|
this.Deserializer = deserializer;
|
|
this.Logger = logger;
|
|
|
|
this.SupportedEncodings.Add(Encoding.UTF8);
|
|
this.SupportedEncodings.Add(Encoding.Unicode);
|
|
this.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/yaml"));
|
|
this.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("text/yaml"));
|
|
}
|
|
|
|
public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding) {
|
|
var request = context.HttpContext.Request;
|
|
|
|
using var reader = context.ReaderFactory(request.Body, encoding);
|
|
var type = context.ModelType;
|
|
|
|
try {
|
|
var content = await reader.ReadToEndAsync();
|
|
var model = this.Deserializer.Deserialize(content, type);
|
|
return await InputFormatterResult.SuccessAsync(model);
|
|
} catch (Exception ex) {
|
|
this.Logger.LogInformation(ex, "Error parsing YAML");
|
|
return await InputFormatterResult.FailureAsync();
|
|
}
|
|
}
|
|
}
|
|
}
|