internal static (string body, bool isBase64Encoded) ConvertAspNetCoreBodyToLambdaBody(Stream aspNetCoreBody, ResponseContentEncoding rcEncoding) { // Do we encode the response content in Base64 or treat it as UTF-8 if (rcEncoding == ResponseContentEncoding.Base64) { // We want to read the response content "raw" and then Base64 encode it byte[] bodyBytes; if (aspNetCoreBody is MemoryStream) { bodyBytes = ((MemoryStream)aspNetCoreBody).ToArray(); } else { using (var ms = new MemoryStream()) { aspNetCoreBody.CopyTo(ms); bodyBytes = ms.ToArray(); } } return(body : Convert.ToBase64String(bodyBytes), isBase64Encoded : true); } else if (aspNetCoreBody is MemoryStream) { return(body : UTF8Encoding.UTF8.GetString(((MemoryStream)aspNetCoreBody).ToArray()), isBase64Encoded : false); } else { aspNetCoreBody.Position = 0; using (StreamReader reader = new StreamReader(aspNetCoreBody, Encoding.UTF8)) { return(body : reader.ReadToEnd(), isBase64Encoded : false); } } }
/// <summary> /// Registers a mapping from a MIME content type to a <see cref="ResponseContentEncoding"/>. /// </summary> /// <remarks> /// The mappings in combination with the <see cref="DefaultResponseContentEncoding"/> /// setting will dictate if and how response content should be transformed before being /// returned to the calling API Gateway instance. /// <para> /// The interface between the API Gateway and Lambda provides for repsonse content to /// be returned as a UTF-8 string. In order to return binary content without incurring /// any loss or corruption due to transformations to the UTF-8 encoding, it is necessary /// to encode the raw response content in Base64 and to annotate the response that it is /// Base64-encoded. /// </para><para> /// <b>NOTE:</b> In order to use this mechanism to return binary response content, in /// addition to registering here any binary MIME content types that will be returned by /// your application, it also necessary to register those same content types with the API /// Gateway using either the console or the REST interface. Check the developer guide for /// further information. /// http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-payload-encodings-configure-with-console.html /// http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-payload-encodings-configure-with-control-service-api.html /// </para> /// </remarks> public void RegisterResponseContentEncodingForContentType(string contentType, ResponseContentEncoding encoding) { _responseContentEncodingForContentType[contentType] = encoding; }