c# - ASP.NET Web API 下载文本

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

我有一个 WebAPI Controller ,需要根据请求下载一些文件,但是当涉及到纯文本文件时,它不会给我浏览器的下载请求。它只给我像 JSON 一样的纯文本响应(在我的例子中,它是一个 JSONP WebAPI)。

我已经从堆栈(和其他站点)检查了其他人的问答,但我仍然一无所获:

这是我当前的代码:

var httpResponse = new HttpResponseMessage(HttpStatusCode.OK);
httpResponse.Content = new StreamContent(new MemoryStream(Encoding.UTF8.GetBytes(content)));
httpResponse.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
httpResponse.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
httpResponse.Content.Headers.ContentDisposition.FileName = "speedcam.txt";
return httpResponse;

这是 Chrome 的响应:

Cache-Control:no-cache

Content-Disposition:attachment; filename=speedcam.txt

Content-Length:17462

Content-Type:application/octet-stream

Date:Mon, 27 Aug 2012 04:53:23 GMT

Expires:-1

Pragma:no-cache

Server:Microsoft-IIS/8.0

X-AspNet-Version:4.0.30319

X-Powered-By:ASP.NET

X-SourceFiles:=?UTF-8?B?TTpcVHJhYmFsaG9cTWFwYVJhZGFyXE1hcGFSYWRhci5XZWJBUEk0XEV4cG9ydGE=?

看起来没问题,但整个文件文本都在 Chrome 开发工具的“响应选项卡”中。

最佳答案

经过大量研究和阅读文本后,我发现AJAX 请求无法下载文件。感谢这两个答案:

JavaScript/jQuery to download file via POST with JSON data

Ajax File Download using Jquery, PHP

关于c# - ASP.NET Web API 下载文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12136478/

相关文章:

c# - asp 日历 0001/01/01

c# - WPF Treeview,如何更改缩进

Asp.net MVC 5 MapRoute 用于多个路由

javascript - $http.post 给出未捕获的类型错误 : Cannot read property 'post' of undefined in angularjs

一次调用中多个集合的 REST API 设计最佳实践

c# - BadHttpRequestException : Reading the request body timed out due to data arriving too slowly. 请参阅 ASP.NET 核心 2.2 上的 MinRequestBodyDataRate

c# - 返回 IAsyncCursor 的 MongoDB C# 驱动程序 Mock 方法

javascript - asp.net mvc 显示 ViewBag 字典到 javascript

Javascript 将月份添加到变量

web-services - 如何在 RESTful Web 服务中使用 mysql 实现基于表单的登录?