【发布时间】:2016-09-20 18:12:42
【问题描述】:
也许有一个非常简单的解决方案...但是我查看的很多线程都没有解决我的问题...我会尽量说清楚。
在 Asp.Net WebApi 项目中有“DownloadController”,目前看起来像:
private HttpResponseMessage CreateFileResponse(string fileName, string originalName, List<string> allowedMimes)
{
// see if file exists
if (!_FileProvider.Exists(fileName))
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
// retrieve mimeType
string mimeType = MimeMapping.GetMimeMapping(fileName);
if (!allowedMimes.Contains(mimeType))
{
mimeType = _generalMimeType;
}
// open the file
FileStream fileStream = _FileProvider.Open(fileName);
// create the response
var response = new HttpResponseMessage();
response.Content = new StreamContent(fileStream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue(mimeType);
response.Content.Headers.ContentLength = _FileProvider.GetLength(fileName);
// if the mimetype is not allowed, download as attachment
if (mimeType == _generalMimeType)
{
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = originalName;
}
return response;
}
//for understanding the above
public DownloadController()
{
_FileProvider = new FileProvider();
}
public interface IFileProvider
{
bool Exists(string name);
FileStream Open(string name);
long GetLength(string name);
}
当对控制器上的某个路由执行简单的 HTTP GET(只是浏览器中的一个 url)时,这段代码可以完美运行。
[Route("Download/Document/{documentid}")]
public HttpResponseMessage GetDocument(Guid documentid)
{
-
-
-
-
return this.CreateFileResponse(fileName, document.filename, allowedMimes);
}
但是现在所有的控制器都通过 asp.net Identity 的 [Authorize] 字段进行了授权。现在,所有请求都需要一个 Authorization 字段,其中的标头中有一个令牌(Bearer “token”)。现在几乎所有的请求都是用 jquery 完成的,你可以简单地添加一个 header 字段。但是对于下载文件,这还没有完成。不过,在 DownloadController 上使用带有令牌标头的 jquery 会给出响应:
.PNG ↵↵ IHDR. .sRGB..gAMA..a pHYs..o........
当我使用令牌发出请求时,提琴手和邮递员也能够显示真实图像。 (不知道pdf文件或其他文件)
但是使用我在 stackoverflow 上尝试的某些 javascript 解决方案设置此数据将无法正常工作.... 图像一直损坏.. 有人可以帮我解决从 javascript 设置此数据的解决方案吗?:)。或者当然是其他解决方案。
【问题讨论】:
-
您是否试图以某种方式在您的 html 代码中呈现来自您的 api 的响应?响应是字节流吗?
-
@Pushpendra 是的,也许故事有点长。但只是想清楚......
标签: javascript jquery png asp.net-identity