[英]How to retrieve files from (jquery) Asp.Net webApi, authorized with Asp.Net Identity
也许有一个非常简单的解决方案...但是我看过的很多线程都无法解决我的问题...我会尽量保持清晰。
在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“令牌”)。 现在,几乎所有请求都是通过jquery完成的,您可以在其中简单地添加标头字段。 但是,对于下载文件,这并未完成。 通过在DownloadController上使用带有令牌头的jquery可以给出响应:
PNG NG IHDR.ssRGB.gAMA.a pHYs..o .......
当我使用令牌进行请求时,提琴手和邮递员也能够显示真实图像。 (不知道pdf文件或其他文件)
但是,使用我在stackoverflow上尝试过的某些javascript解决方案设置此数据将无法正常工作。...图像始终不可用。有人可以提供解决方案来从javascript设置此数据吗? 当然还有其他解决方案。
有诸如groupdocs之类的工具,可将流转换为htmlresponse,图像和本机,您可以使用它们在html代码中进行呈现。 您可以在api调用中执行此操作,以便将响应作为字节流发送。 groupdocs-library
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.