下载文件请求返回JSON,而不是服务器上ASP.NET Web API中的文件



我正在尝试在ASP.NET Web API中下载CSV文件。这是我的代码,它在本地工作。

[Route("{name?}")]
public HttpResponseMessage Get(string name = "DownloadFile")
{
name = name.EndsWith(".csv") ? name : $"{name}.csv";
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write("Hello, World!");
writer.Flush();
stream.Position = 0;
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(stream.ToArray())
};
result.Content.Headers.Add("x-filename", name);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = name
};
return result;
}

该文件正在本地主机的浏览器中下载。我在服务器上部署了相同的代码,它返回了一个JSON而不是下载文件。

JSON如下所示:

{
"version": {
"major": 1,
"minor": 1,
"build": -1,
"revision": -1,
"majorRevision": -1,
"minorRevision": -1
},
"content": {
"headers": [
{
"key": "x-filename",
"value": [
"test.csv"
]
},
{
"key": "Content-Type",
"value": [
"application/octet-stream"
]
},
{
"key": "Content-Disposition",
"value": [
"attachment; filename=test.csv"
]
}
]
},
"statusCode": 200,
"reasonPhrase": "OK",
"headers": [],
"requestMessage": null,
"isSuccessStatusCode": true
}

我已经在IIS中检查了mime类型,它就在那里。我遗漏了什么吗??

我在使用WebApi时遇到了类似的问题,当在Visual Studio中调试时,以及当在本地部署到IIS时,WebApi在本地运行良好。在我的服务器上,我得到了如上所述的JSON响应。在一次新的部署之后,我看到了一个关于丢失方法的新错误:

找不到方法:'System.Net.Http.HttpRequestMessageSystem.Web.Http.Controllers.HttpActionContext.get_Request(('.

解决方案是添加一个新的绑定重定向。也许这对你来说是一个有效的解决方案。

<dependentAssembly>
<assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.2.0.0" />
</dependentAssembly>

这通常适用于我的

private ActionResult GetFile(string path, string fileName)
{
var memory = new MemoryStream();
using (var stream = new FileStream(path + fileName, FileMode.Open))
{
stream.CopyTo(memory);
}
memory.Position = 0;
var file = File(memory, GetContentType(path + fileName), Path.GetFileName(path + fileName));
file.FileDownloadName = fileName;
return file;
}
private string GetContentType(string path)
{
var types = GetMimeTypes();
var ext = Path.GetExtension(path).ToLowerInvariant();
return types[ext];
}
//find out what .csv is these won't work for you
private Dictionary<string, string> GetMimeTypes()
{
return new Dictionary<string, string>
{
//{".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation" }
//{".docx", "application/vnd.ms-word"}
//{".pdf", "application/pdf"}
};
}

然后对于控制器来说,像这样调用

public FileResult GeneratePoExportDocument(params)
{
return GetFile(HostingEnvironment.ApplicationPhysicalPath + "Documents", "\mydoc.docx");
}

之后,它应该自动下载该文件。

编辑:修复控制器方法的返回类型

尝试mimetypes

application/vnd.ms-excel

text/csv

我遇到了类似的问题,在这里回答了另一个SO问题,帮助我解决了这个问题。

显然是System.Net.Http程序集中的冲突导致了HttpResponse的异常行为。我卸载了System.Net.Http nuget包并将其重新安装。然后我检查了web.config中生成的绑定重定向.

最新更新