Skip to content

Instantly share code, notes, and snippets.

@NDiiong
Created February 17, 2022 05:58
Show Gist options
  • Save NDiiong/fd729946335767973e9bd0cb8134569d to your computer and use it in GitHub Desktop.
Save NDiiong/fd729946335767973e9bd0cb8134569d to your computer and use it in GitHub Desktop.
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Net.Http.Headers;
using System.Threading.Tasks;
namespace ActionResults;
public class FileActionResult : IActionResult
{
private readonly byte[] _contentFile;
private readonly string _contentType;
private readonly string _filename;
public FileActionResult(byte[] contentFile, string filename)
{
_contentFile = contentFile;
_filename = filename;
_contentType = GetContentType(filename);
}
public async Task ExecuteResultAsync(ActionContext context)
{
context.HttpContext.Response.Headers["x-file-name"] = _filename;
context.HttpContext.Response.Headers[HeaderNames.ContentType] = _contentType;
context.HttpContext.Response.Headers[HeaderNames.ContentLength] = _contentFile.Length.ToString(provider: default);
context.HttpContext.Response.Headers[HeaderNames.ContentDisposition] = $"{System.Net.Mime.DispositionTypeNames.Inline}; filename=\"{_filename}\";";
await context.HttpContext.Response.Body.WriteAsync(_contentFile, 0, _contentFile.Length).ConfigureAwait(false);
}
private string GetContentType(string fileName)
{
var provider = new FileExtensionContentTypeProvider();
if (!provider.TryGetContentType(fileName, out string contentType))
contentType = "application/octet-stream";
return contentType;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment