public static void DataFormatBody <T>(this BrowserContext browserContext, DataFormat format, T model) { switch (format) { case DataFormat.Json: browserContext.JsonBody(model); break; case DataFormat.Proto: var descriptor = ProtobufResponse.GetDescriptor(typeof(T)); object value = SimpleValue.FromValue(model); if (value == null) { value = model; } var bytes = descriptor.Write(value); browserContext.Body(new MemoryStream(bytes), "application/x-protobuf"); browserContext.Header("Content-Length", bytes.Length.ToString()); break; default: throw new NotImplementedException(); } }
public ProtobufResponse(object model) { ContentType = ContentType_Protobuf; StatusCode = HttpStatusCode.OK; Contents = model == null ? NoBody : (stream => { var descriptor = GetDescriptor(model.GetType()); byte[] bytes; if (model is IEnumerable collection) { bytes = descriptor.WriteLenDelimitedStream(collection); } else { var simpleModel = SimpleValue.FromValue(model); if (simpleModel != null) { bytes = descriptor.Write(simpleModel); } else { bytes = descriptor.Write(model); } } stream.Write(bytes, 0, bytes.Length); }); }