gpt4 book ai didi

asp.net - 如何使用 ASP.NET Core 创建多部分 HTTP 响应

转载 作者:行者123 更新时间:2023-12-03 21:44:09 27 4
gpt4 key购买 nike

我想在我的 ASP.NET Core Controller 中创建一个操作方法,它返回一个包含多个文件的多部分 HTTP 响应。我知道使用 .zip 文件是网站的推荐方法,但我正在考虑使用这样的 API 请求。

我已经能够的例子find在 ASP.NET Core 示例中,上传文件时处理多部分 HTTP 请求。就我而言,我想下载文件。

更新

我提出了以下 GitHub 问题:#4933

最佳答案

我写了一个更通用的 MultipartResult仅从 ActionResult 继承的类:

使用示例

[Route("[controller]")]
public class MultipartController : Controller
{
private readonly IHostingEnvironment hostingEnvironment;

public MultipartController(IHostingEnvironment hostingEnvironment)
{
this.hostingEnvironment = hostingEnvironment;
}

[HttpGet("")]
public IActionResult Get()
{
return new MultipartResult()
{
new MultipartContent()
{
ContentType = "text/plain",
FileName = "File.txt",
Stream = this.OpenFile("File.txt")
},
new MultipartContent()
{
ContentType = "application/json",
FileName = "File.json",
Stream = this.OpenFile("File.json")
}
};
}

private Stream OpenFile(string relativePath)
{
return System.IO.File.Open(
Path.Combine(this.hostingEnvironment.WebRootPath, relativePath),
FileMode.Open,
FileAccess.Read);
}
}

执行
public class MultipartContent
{
public string ContentType { get; set; }

public string FileName { get; set; }

public Stream Stream { get; set; }
}

public class MultipartResult : Collection<MultipartContent>, IActionResult
{
private readonly System.Net.Http.MultipartContent content;

public MultipartResult(string subtype = "byteranges", string boundary = null)
{
if (boundary == null)
{
this.content = new System.Net.Http.MultipartContent(subtype);
}
else
{
this.content = new System.Net.Http.MultipartContent(subtype, boundary);
}
}

public async Task ExecuteResultAsync(ActionContext context)
{
foreach (var item in this)
{
if (item.Stream != null)
{
var content = new StreamContent(item.Stream);

if (item.ContentType != null)
{
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(item.ContentType);
}

if (item.FileName != null)
{
var contentDisposition = new ContentDispositionHeaderValue("attachment");
contentDisposition.SetHttpFileName(item.FileName);
content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
content.Headers.ContentDisposition.FileName = contentDisposition.FileName;
content.Headers.ContentDisposition.FileNameStar = contentDisposition.FileNameStar;
}

this.content.Add(content);
}
}

context.HttpContext.Response.ContentLength = content.Headers.ContentLength;
context.HttpContext.Response.ContentType = content.Headers.ContentType.ToString();

await content.CopyToAsync(context.HttpContext.Response.Body);
}
}

关于asp.net - 如何使用 ASP.NET Core 创建多部分 HTTP 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38069730/

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