public async Task ExecuteResultAsync(ActionContext context) { HttpContent httpContent = new StringContent(_result.ToJson(_format), Encoding.UTF8, MediaTypes.Application.Json); if (_attachments) { string boundary = Guid.NewGuid().ToString(); httpContent = new MultipartContent("mixed", boundary) { httpContent }; var attachmentsWithPayload = _result.Statements.SelectMany(x => x.Attachments.Where(a => a.Payload != null)); foreach (var attachment in attachmentsWithPayload) { ((MultipartContent)httpContent).AddAttachment(attachment); } } foreach (var header in httpContent.Headers) { context.HttpContext.Response.Headers.Add( header.Key, new StringValues(header.Value.ToArray()) ); } await httpContent.CopyToAsync(context.HttpContext.Response.Body); }
public Task ExecuteResultAsync(ActionContext context) { var stringContent = new StringContent(result.ToJson(format), Encoding.UTF8, MediaTypes.Application.Json); var attachmentsWithPayload = result.Statements.SelectMany(x => x.Attachments.Where(a => a.Payload != null)); if (attachmentsWithPayload.Count() > 0) { string boundary = Guid.NewGuid().ToString(); using var multipart = new MultipartContent("mixed", boundary) { stringContent }; foreach (var attachment in attachmentsWithPayload) { var byteArrayContent = new ByteArrayContent(attachment.Payload); var attachmentMediaType = MediaTypeHeaderValue.Parse(attachment.ContentType); byteArrayContent.Headers.ContentType = attachmentMediaType; byteArrayContent.Headers.Add(ApiHeaders.ContentTransferEncoding, "binary"); byteArrayContent.Headers.Add(ApiHeaders.XExperienceApiHash, attachment.SHA2); multipart.Add(byteArrayContent); } // Write Content-Type header with Boundary parameter var mediaType = MediaTypeHeaderValue.Parse(MediaTypes.Multipart.Mixed); mediaType.Parameters.Add(new NameValueHeaderValue("boundary", boundary)); context.HttpContext.Response.ContentType = mediaType.ToString(); return(multipart.CopyToAsync(context.HttpContext.Response.Body)); } return(stringContent.CopyToAsync(context.HttpContext.Response.Body)); }