Created
February 17, 2022 05:58
-
-
Save NDiiong/fd729946335767973e9bd0cb8134569d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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