c# - 使用 HTTP GET 请求从 Web Api 返回文件内容

标签 c# asp.net .net rest asp.net-web-api

<分区>

客户端将向我们的 Web API 服务发出 GET 请求,我们需要使用指定的文件响应该请求。

文件内容将是像这样的字节数组:

byte[] fileContent = Convert.FromBase64String(retrievedAnnotation.DocumentBody);

如何将上述文件内容作为文件响应GET请求?

我已经创建了一个 Controller :

[Route("Note({noteGuid:guid})/attachment", Name = "GetAttachment")]
[HttpGet]
public async Task<object> GetAttachment(Guid noteGuid)
{

    return new object();
}

我如何将 fileContent 返回到 GET 请求而不是新对象?

最佳答案

您可以使用以下方法从 web api 返回文件内容

public HttpResponseMessage GetAttachment(Guid noteGuid)
{
    byte[] content = Convert.FromBase64String(retrievedAnnotation.DocumentBody);
    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
    response.Content = new ByteArrayContent(content);
    response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
    response.Content.Headers.ContentDisposition.FileName = "fileName.txt";
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");

    return response;
}

关于c# - 使用 HTTP GET 请求从 Web Api 返回文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40065874/

相关文章:

c# - Pcap.net 与 Sharppcap

c# - 参数字典包含不可为空类型 'idd' 的参数 'System.Int32' 的空条目

c# - 设置数据绑定(bind) DropDownList 的 SelectedValue

c# - 如果仅更改内部版本号或修订版号,则定位 GAC 程序集

c# - 移除对继承的抽象类引用的依赖

c# - 如何显示我的电脑文件夹中的元素?

c# - 涟漪效应 : OutOfMemoryException

c# - 将对象添加到列表,更改所有其他列表对象

c# - 有关显示图形和图表的建议

html - GridView 对比HTML 表格 (ASP.net 2.0)