客户端将向我们的 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;
}