gpt4 book ai didi

asp.net - MVC 6 WebAPI 返回序列化的 HttpResponseMessage 而不是文件流

转载 作者:行者123 更新时间:2023-12-01 17:24:05 25 4
gpt4 key购买 nike

我正在尝试让我的 ASP.Net 5 MVC 6 WebAPI 项目输出一个文件,以响应 HttpGET 请求。

该文件来自 Azure 文件共享,但它可以是包含二进制文件的任何流。

在我看来,MVC 序列化响应对象,并返回结果 JSON,而不是返回响应对象本身。

这是我的 Controller 方法:

    [HttpGet]
[Route("GetFile")]
public HttpResponseMessage GetFile(string Username, string Password, string FullName)
{

var client = new AzureFilesClient.AzureFilesClient(Username, Password);
Stream azureFileStream = client.GetFileStream(FullName).Result;
var fileName = Path.GetFileName(FullName);

using (HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK))
{
response.Content = new StreamContent(azureFileStream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = fileName };
return response;
}
}

AzureFilesClient 上的 GetFileStream 方法位于此处,尽管流源可以是包含二进制文件内容的任何内容:

    public async Task<Stream> GetFileStream(string fileName)
{
var uri = new Uri(share.Uri + "/" + fileName);
var file = new CloudFile(uri, credentials);

using (var stream = new MemoryStream())
{
await file.DownloadToStreamAsync(stream);
stream.Seek(0, SeekOrigin.Begin);
return stream;
}
}

编辑:以下是 JSON 响应的示例:

{
"Version": {
"Major": 1,
"Minor": 1,
"Build": -1,
"Revision": -1,
"MajorRevision": -1,
"MinorRevision": -1
},
"Content": {
"Headers": [
{
"Key": "Content-Type",
"Value": [
"application/octet-stream"
]
},
{
"Key": "Content-Disposition",
"Value": [
"attachmentx; filename=\"samplefile.docx\""
]
}
]
},
"StatusCode": 200,
"ReasonPhrase": "OK",
"Headers": [],
"RequestMessage": null,
"IsSuccessStatusCode": true
}

最佳答案

经过阅读文档以及一些尝试和错误,问题已经解决。

Azure 部分是使用 nuGet 包“WindowsAzure.Storage”(4.4.1-预览版)制作的

首先是 JSON 序列化的输出。这需要返回自定义操作结果。

using Microsoft.AspNet.Mvc;
using System.IO;
using System.Threading.Tasks;

public class FileResultFromStream : ActionResult
{
public FileResultFromStream(string fileDownloadName, Stream fileStream, string contentType)
{
FileDownloadName = fileDownloadName;
FileStream = fileStream;
ContentType = contentType;
}

public string ContentType { get; private set; }
public string FileDownloadName { get; private set; }
public Stream FileStream { get; private set; }

public async override Task ExecuteResultAsync(ActionContext context)
{
var response = context.HttpContext.Response;
response.ContentType = ContentType;
context.HttpContext.Response.Headers.Add("Content-Disposition", new[] { "attachment; filename=" + FileDownloadName });
await FileStream.CopyToAsync(context.HttpContext.Response.Body);
}
}

现在获取从 Azure 文件共享(或任何其他异步流源)流式传输的二进制数据

using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.File;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;

public async Task<Stream> GetFileStreamAsync(string fileName)
{
var uri = new Uri(share.Uri + "/" + fileName);
var file = new CloudFile(uri, credentials);

// Note: Do not wrap the stream variable in a Using, since it will close the stream too soon.
var stream = new MemoryStream();
await file.DownloadToStreamAsync(stream);
stream.Seek(0, SeekOrigin.Begin);
return stream;
}

最后是 Controller 代码。请注意 IActionResult 接口(interface)的使用。

    [HttpGet]
[Route("GetFile")]
public async Task<IActionResult> GetFile(string username, string password, string fullName)
{
var client = new AzureFilesClient.AzureFilesClient(username, password);
Stream stream = await client.GetFileStreamAsync(fullName);
string fileName = Path.GetFileName(fullName);
return new CustomActionResults.FileResultFromStream(fileName, stream, "application/msword");
}

注意:此示例仅用于 Word 文件,您可能需要考虑将 ContentType 参数设为动态,而不是像这样的静态参数。

关于asp.net - MVC 6 WebAPI 返回序列化的 HttpResponseMessage 而不是文件流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30240468/

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