コード例 #1
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="cloudEvent">CloudEvent</param>
        /// <param name="contentMode">Content mode. Structured or binary.</param>
        /// <param name="formatter">Event formatter</param>
        public CloudEventHttpContent(CloudEvent cloudEvent, ContentMode contentMode, ICloudEventFormatter formatter)
        {
            if (contentMode == ContentMode.Structured)
            {
                inner = new InnerByteArrayContent(formatter.EncodeStructuredEvent(cloudEvent, out var contentType));
                // This is optional in the specification, but can be useful.
                MapHeaders(cloudEvent, includeDataContentType: true);
                Headers.ContentType = new MediaTypeHeaderValue(contentType.MediaType);
                return;
            }

            // TODO: Shouldn't we use the formatter in all cases? If I have a JSON formatter and
            // If we specify that the the data is a byte array, I'd expect to end up with a base64-encoded representation...
            if (cloudEvent.Data is byte[])
            {
                inner = new InnerByteArrayContent((byte[])cloudEvent.Data);
            }
            else if (cloudEvent.Data is string)
            {
                inner = new InnerStringContent((string)cloudEvent.Data);
            }
            else if (cloudEvent.Data is Stream)
            {
                inner = new InnerStreamContent((Stream)cloudEvent.Data);
            }
            else
            {
                inner = new InnerByteArrayContent(formatter.EncodeData(cloudEvent.Data));
            }

            // We don't require a data content type if there isn't any data.
            // We may not be able to tell whether the data is empty or not, but we're lenient
            // in that case.
            var dataContentType = cloudEvent.DataContentType;

            if (dataContentType is object)
            {
                var mediaType = new ContentType(dataContentType).MediaType;
                Headers.ContentType = new MediaTypeHeaderValue(mediaType);
            }
            else if (TryComputeLength(out var length) && length != 0L)
            {
                throw new ArgumentException(Strings.ErrorContentTypeUnspecified, nameof(cloudEvent));
            }
            MapHeaders(cloudEvent, includeDataContentType: false);
        }