更新:正如我提到的,我改变了我的行动方法,没有成功。查看屏幕截图
结果是一样的,不管:
简单总结一下我的问题:一切都在 dot net core 2.0. 我有一个 WebAPI(单独的项目)及其控制器(与 SQL Server 对话)。我的客户端应用程序是一个 ASP.NET Core MVC Web 应用程序,其控制器的操作方法将返回一个文件。在我的情况下,一个字节流。当我打开从运行客户端应用程序的浏览器下载的文件时,该文件就像一些以 JSON 样式格式包装的 HttpResponseMessage。
API 控制器
[Route("api/[controller]")]
public class GasDownloadController : Controller
{
private readonly IGasesRepository _repository;
public GasDownloadController(IGasesRepository repository)
{
_repository = repository;
}
[HttpGet]
public HttpResponseMessage Export([FromQuery] Gas gas)
{
var item = _repository.GetGasesService(gas);
byte[] outputBuffer = null;
using (MemoryStream tempStream = new MemoryStream())
{
using (StreamWriter writer = new StreamWriter(tempStream))
{
FileWriter.WriteDataTable(item, writer, true);
}
outputBuffer = tempStream.ToArray();
}
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new ByteArrayContent(outputBuffer);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = $"ENVSdata.csv" };
return result;
}
}
助手类
public class FileWriter
{
public static void WriteDataTable(DataTable sourceTable, TextWriter writer, bool includeHeaders)
{
if (includeHeaders)
{
writer.WriteLine("sep=,");
IEnumerable<string> headerValues = sourceTable.Columns
.OfType<DataColumn>()
.Select(column => QuoteValue(column.ColumnName));
writer.WriteLine(String.Join(",", headerValues));
}
IEnumerable<String> items = null;
foreach (DataRow row in sourceTable.Rows)
{
items = row.ItemArray.Select(o => QuoteValue(o?.ToString() ?? String.Empty));
writer.WriteLine(String.Join(",", items));
}
writer.Flush();
}
private static string QuoteValue(string value)
{
return String.Concat("\"",
value.Replace("\"", "\"\""), "\"");
}
}
MVC 控制器
public class DownloadsController : Controller
{
private IGasesRepository _repository;
public DownloadsController(IGasesRepository repository)
{
_repository = repository;
}
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public async Task<FileResult> GetFile(Gas inputGas)
{
var model = await _repository.GasDownloads(inputGas);
return File(model, "text/csv", "data.csv");
}
}
回购
public class GasesRepository : IGasesRepository
{
public IEnumerable<Gas> Gases { get; set; }
public byte[] CsvBytes { get; set; }
private string BaseGasApiUrl = "http://localhost:XXXX";
private string BaseDwnlApiUrl = "http://localhost:XXXX";
public async Task<IEnumerable<Gas>> GasService(Gas gasCompound)
{
//code omitted for brewity
}
public async Task<byte[]> GasDownloads(Gas gasCompound)
{
UriBuilder builder = new UriBuilder(BaseDwnlApiUrl);
builder.Query =
$"XXXXX";
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(BaseDwnlApiUrl);
client.DefaultRequestHeaders.Accept.Clear();
try
{
HttpResponseMessage responseMessage = await client.GetAsync(builder.Uri);
if (responseMessage.IsSuccessStatusCode)
{
var apiResult = responseMessage.Content.ReadAsByteArrayAsync().Result;
CsvBytes = apiResult;
}
else
return null;
}
catch (HttpRequestException downloadRequestException)
{
throw new HttpRequestException(downloadRequestException.Message);
}
catch (ArgumentNullException argsNullException)
{
throw new ArgumentNullException(argsNullException.Message);
}
}
return CsvBytes;
}
}
结果
因此,当我打开浏览器下载的文件(f.ex:Excel)时,它是一个 CSV 文件,但不是列和行以及其中的数据,它只是一个
{
"version": {
"major": 1,
"minor": 1,
"build": -1,
"revision": -1,
"majorRevision": -1,
"minorRevision": -1
},
"content": {
"headers": [
{
"key": "Content-Type",
"value": [
"text\/csv"
]
},
{
"key": "Content-Disposition",
"value": [
"attachment; filename=data.csv"
]
}
]
},
"statusCode": 200,
"reasonPhrase": "OK",
"headers": [
],
"requestMessage": null,
"isSuccessStatusCode": true
}
我已经尝试过的:
如果我调试我可以看到我得到了一个合法/有效的字节数组,但不知何故发生了一些魔法,或者它是如此明显和大以至于我看不到树木的树木?
我尝试更改我的 MVC 控制器 Action 方法以返回许多可能类型的事物(IActionResult、IHttpResponse、FileContentResult 等......)。
我在 MVC 5 中有相同的项目,没有问题,得到一个包含我的数据行和列的有效 CSV 文件。
任何帮助将不胜感激!