gpt4 book ai didi

c# - 在 asp.net/mvc 中的 Controller 内的操作中向 http 响应添加 header

转载 作者:太空狗 更新时间:2023-10-29 17:40:22 27 4
gpt4 key购买 nike

我使用 filestream.write 将数据从服务器流式传输到客户端以供下载。在这种情况下,发生的情况是我能够下载该文件,但它在我的浏览器中没有显示为已下载。 “另存为”的弹出窗口和“下载栏”都不会出现在下载部分。环顾四周,我想我需要在响应 header 中包含“某物”,以告诉浏览器此响应有一个附件。我也想设置 cookie。为此,这就是我正在做的事情:

        [HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename=" & name)]
public ActionResult Download(string name)
{
// some more code to get data in inputstream.

using (FileStream fs = System.IO.File.OpenWrite(TargetFile))
{
byte[] buffer = new byte[SegmentSize];
int bytesRead;
while ((bytesRead = inputStream.Read(buffer, 0, SegmentSize)) > 0)
{
fs.WriteAsync(buffer, 0, bytesRead);
}
}
}
return RedirectToAction("Index");
}

我收到错误消息:“System.web.httpcontext.current 是一个属性,用作类型。”

我是否在正确的位置更新标题?还有其他方法吗?

最佳答案

是的,你做错了方法试试这个,你应该在你的 Action 中添加标题而不是作为你方法的属性标题。

HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename=" & name)

Request.RequestContext.HttpContext.Response.AddHeader("Content-Disposition", "Attachment;filename=" & name)

更新据我了解,您正在对您的 Controller /操作进行 ajax 调用,这将无法通过直接调用操作来下载文件。您可以通过这种方式实现它。

public void Download(string name)
{
//your logic. Sample code follows. You need to write your stream to the response.

var filestream = System.IO.File.ReadAllBytes(@"path/sourcefilename.pdf");
var stream = new MemoryStream(filestream);
stream.WriteTo(Response.OutputStream);
Response.AddHeader("Content-Disposition", "Attachment;filename=targetFileName.pdf");
Response.ContentType = "application/pdf";
}

    public FileStreamResult Download(string name)
{
var filestream = System.IO.File.ReadAllBytes(@"path/sourcefilename.pdf");
var stream = new MemoryStream(filestream);


return new FileStreamResult(stream, "application/pdf")
{
FileDownloadName = "targetfilename.pdf"
};
}

在你的 JS 按钮中点击你可以做类似的事情。

 $('#btnDownload').click(function () {
window.location.href = "controller/download?name=yourargument";
});

关于c# - 在 asp.net/mvc 中的 Controller 内的操作中向 http 响应添加 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16094652/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com