Created
May 29, 2022 18:00
-
-
Save fabiomaulo/f0da1df87130499e2cdbeda546fc281b to your computer and use it in GitHub Desktop.
Return a view as download html file (netcore 3.1)
This file contains 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
public class HtmlFileResult : ActionResult | |
{ | |
private readonly string fileDownloadName; | |
private readonly ViewResult viewToRender; | |
public HtmlFileResult(ViewResult viewToRender, string fileDownloadName) | |
{ | |
if (string.IsNullOrWhiteSpace(fileDownloadName)) | |
{ | |
throw new ArgumentException($"'{nameof(fileDownloadName)}' cannot be null or whitespace.", nameof(fileDownloadName)); | |
} | |
this.viewToRender = viewToRender ?? throw new ArgumentNullException(nameof(viewToRender)); | |
this.fileDownloadName = fileDownloadName; | |
} | |
public override async Task ExecuteResultAsync(ActionContext context) | |
{ | |
const int BufferSize = 64 * 1024; | |
var viewEngine = viewToRender.ViewEngine | |
?? (IViewEngine)context.HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine)); | |
var viewResult = viewEngine.FindView(context, viewToRender.ViewName, true); | |
if (viewResult is null) | |
{ | |
throw new InvalidOperationException($"'{viewToRender.ViewName}' does not match any available view."); | |
} | |
var response = context.HttpContext.Response; | |
response.StatusCode = 200; | |
response.ContentType = "text/html"; | |
var contentDisposition = new ContentDispositionHeaderValue("attachment"); | |
contentDisposition.SetHttpFileName(fileDownloadName); | |
response.Headers.Add("Content-Disposition", contentDisposition.ToString()); | |
using (TextWriter textWriter = new StreamWriter(response.Body, Encoding.UTF8, | |
bufferSize: BufferSize, leaveOpen: true)) | |
{ | |
IView view = viewResult.View; | |
var viewContext = new ViewContext(context, view, viewToRender.ViewData, viewToRender.TempData, textWriter, new HtmlHelperOptions()); | |
await view.RenderAsync(viewContext); | |
await textWriter.FlushAsync(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment