Эквивалент FileResult.NET MVC в веб-формах
Я использую FileResult в качестве возвращаемого значения для функции в MVC, которая возвращает файл PDF.
Какой тип возврата я должен использовать в веб-формах?
Спасибо
public FileResult PrintPDFVoucher(object sender, EventArgs e)
{
PdfDocument outputDoc = new PdfDocument();
PdfDocument pdfDoc = PdfReader.Open(
Server.MapPath(ConfigurationManager.AppSettings["Template"]),
PdfDocumentOpenMode.Import
);
MemoryStream memory = new MemoryStream();
try
{
//Add pages to the import document
int pageCount = pdfDoc.PageCount;
for (int i = 0; i < pageCount; i++)
{
PdfPage page = pdfDoc.Pages[i];
outputDoc.AddPage(page);
}
//Target specifix page
PdfPage pdfPage = outputDoc.Pages[0];
XGraphics gfxs = XGraphics.FromPdfPage(pdfPage);
XFont bodyFont = new XFont("Arial", 10, XFontStyle.Regular);
//Save
outputDoc.Save(memory, true);
gfxs.Dispose();
pdfPage.Close();
}
finally
{
outputDoc.Close();
outputDoc.Dispose();
}
var result = new FileContentResult(memory.GetBuffer(), "text/pdf");
result.FileDownloadName = "file.pdf";
return result;
}
2 ответа
Решение
В ASP.NET Webforms вам нужно будет записать файл в поток ответа вручную. В веб-формах нет абстракции результата.
Response.ContentType = "Application/pdf";
//Write the generated file directly to the response stream
Response.BinaryWrite(memory);//Response.WriteFile(FilePath); if you have a physical file you want them to download
Response.End();
Этот код не проверен, но это должно привести вас к общему направлению.
Классический ASP.NET не имеет представления о типе возвращаемого значения. Для этого можно создать пользовательскую страницу / обработчик.ashx для обслуживания файла.
Ваш код для этого файла должен выглядеть примерно так:
public class Download : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
PdfDocument outputDoc = new PdfDocument();
PdfDocument pdfDoc = PdfReader.Open(
Server.MapPath(ConfigurationManager.AppSettings["Template"]),
PdfDocumentOpenMode.Import
);
MemoryStream memory = new MemoryStream();
try
{
//Add pages to the import document
int pageCount = pdfDoc.PageCount;
for (int i = 0; i < pageCount; i++)
{
PdfPage page = pdfDoc.Pages[i];
outputDoc.AddPage(page);
}
//Target specifix page
PdfPage pdfPage = outputDoc.Pages[0];
XGraphics gfxs = XGraphics.FromPdfPage(pdfPage);
XFont bodyFont = new XFont("Arial", 10, XFontStyle.Regular);
//Save
Response.ContentType = ""text/pdf"";
Response.AppendHeader("Content-Disposition","attachment; filename=File.pdf");
outputDoc.Save(Response.OutputStream, true);
gfxs.Dispose();
pdfPage.Close();
}
finally
{
outputDoc.Close();
outputDoc.Dispose();
}
}
public bool IsReusable
{
get
{
return false;
}
}
}