public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType) { string fileName = "data"; // Look for ExcelDocumentAttribute on class. var itemType = FormatterUtils.GetEnumerableItemType(type); var excelDocumentAttribute = FormatterUtils.GetAttribute <ExcelDocumentAttribute>(itemType ?? type); if (excelDocumentAttribute != null && !string.IsNullOrEmpty(excelDocumentAttribute.FileName)) { // If attribute exists with file name defined, use that. fileName = excelDocumentAttribute.FileName; } else { // Get the raw request URI. string rawUri = _httpContextAccessor.HttpContext?.Request?.GetDisplayUrl(); if (string.IsNullOrEmpty(rawUri) != false) { // Remove query string if present. int queryStringIndex = rawUri.IndexOf('?'); if (queryStringIndex > -1) { rawUri = rawUri.Substring(0, queryStringIndex); } } // Otherwise, use either the URL file name component or just "data". fileName = Path.GetFileName(_httpContextAccessor.HttpContext?.Request?.Path) ?? "data"; } // Add XLSX extension if not present. if (string.IsNullOrEmpty(_fileExtension)) { if (!fileName.EndsWith("xlsm", StringComparison.CurrentCultureIgnoreCase)) { fileName += ".xlsm"; } } else { if (!fileName.EndsWith(string.Format(".{0}", _fileExtension), StringComparison.CurrentCultureIgnoreCase)) { fileName += string.Format(".{0}", _fileExtension); } } // Set content disposition to use this file name. headers.ContentDisposition = new ContentDispositionHeaderValue("inline") { FileName = fileName }; base.SetDefaultContentHeaders(type, headers, mediaType); }
public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, System.Net.Http.HttpContent content, System.Net.TransportContext transportContext) { // Create a document builder. var document = new SqadXlsxDocumentBuilder(writeStream); if (value == null) { return(document.WriteToStream()); } var valueType = value.GetType(); // Get the item type. var itemType = FormatterUtils.IsSimpleType(valueType) ? null : FormatterUtils.GetEnumerableItemType(valueType); // If a single object was passed, treat it like a list with one value. if (itemType == null) { itemType = valueType; } // Used if no other matching serialiser can be found. IXlsxSerializer serializer = null; // Determine if a more specific serialiser might apply. if (Serializers != null) { foreach (var s in Serializers) { if (!s.CanSerializeType(valueType, itemType) || s.SerializerType != _serializerType) { continue; } serializer = s; break; } } serializer?.Serialize(itemType, value, document, null, null, null); if (!document.IsVBA) { content.Headers.ContentDisposition.FileName = content.Headers.ContentDisposition.FileName.Replace("xlsm", "xlsx"); } return(document.WriteToStream()); }