public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext) { if (ReferenceEquals(value, null)) { return _baseFormatter.WriteToStreamAsync(typeof (HalModel), new HalModel(), writeStream, content, transportContext); } var valType = value.GetType(); if (valType != typeof(HalModel)) { if (valType.IsArray || value is IEnumerable<object>) { var data = value as IEnumerable<object>; value = new HalModel(new { Count = data.Count() }) .AddLinks(new HalLink("self", RequestPath)) .AddEmbeddedCollection("values", data); } else { value = new HalModel(value); } type = typeof(HalModel); } var model = value as HalModel; model.Config.IsRoot = true; model.Config.RequestPathBase = RequestPathBase; model.Config.Expands = Expands; return _baseFormatter.WriteToStreamAsync(type, model, writeStream, content, transportContext); }
internal static List<HalModel> GetFlattenedModelList(HalModel model, List<HalModel> stack = null) { if (stack == null) stack = new List<HalModel>(); foreach (var embedded in model.Embeds.Values.SelectMany(m => m)) { GetFlattenedModelList(embedded, stack); } stack.Add(model); return stack; }
public async Task Write_To_Stream_test() { using (var stream = new MemoryStream()) { var content = new StringContent(""); var formatter = new HalMediaTypeFormatter(); var model = new HalModel(new { test = 1 }); Assert.NotNull(formatter); await formatter.WriteToStreamAsync(typeof(HalModel), model, stream, content, null); // Reset the position to ensure it can read stream.Position = 0; var reader = new StreamReader(stream); string result = await reader.ReadToEndAsync(); Assert.Equal("{\"test\":1}", result); } }