【发布时间】:2015-09-20 01:32:28
【问题描述】:
我有一个使用 owin 身份验证和不记名令牌的 Web api。我将同时拥有 web 和 wpf (vb) 客户端,它们需要在经过身份验证时从 api 请求图像文件。未经身份验证的请求不应返回图像。
到目前为止,我有一个在未经过身份验证的情况下返回图像的可行解决方案:
我在 c# 中的控制器操作:
//[Authorize]
public HttpResponseMessage GetFile()
{
string localFilePath = "C:/Path/ImageOnServerDisk.png";
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = "myImage.png";
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/png");
return response;
}
这就是我在网络客户端上的显示方式:
<img src="/api/Secure/GetFile" id="img" />
这很好用,但是当然,当我取消注释上述操作中的授权属性时,图像文件不会显示,并且我收到一条 401(未授权)消息,用于调用 GetFile 操作的 GET 消息。这是因为 GET 请求上没有访问令牌。
我可以使用 jQuery 通过 ajax 获取,但我不知道如何将结果设置为 img 元素。
如何为调用 img src 中的操作的 http GET 请求设置访问令牌,或将图像内容设置到 jQuery 中的 img 元素中?还是有更好的方法来完全做到这一点?
【问题讨论】:
-
如果您带回 Authorize 属性,这将不起作用。我的操作方法在 ApiController 下,我尝试生成指向我的控制器的
标记,但它失败了。因为没有要验证的用户上下文。有任何想法吗?我想我需要添加 AspNet.Mvc 并注册一个普通路由,而不是 HTTP 路由。
标签: c# jquery asp.net-web-api asp.net-web-api2 owin