【问题标题】:Return image from web api controller action while authenticated通过身份验证时从 Web api 控制器操作返回图像
【发布时间】: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


【解决方案1】:

我认为“使用 jQuery 通过 ajax 获取”会起作用。我们可以将令牌设置为请求头。您可以尝试下面的 api 控制器代码:

        var root = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
        var path = Path.Combine(root, "App_Data/Koala.jpg");

        var bytes = File.ReadAllBytes(path);
        var base64 = Convert.ToBase64String(bytes);

        return "data:image/jpeg;base64," + base64;

下面是一些javascript sn-p

    $.ajax({
        url: '//localhost:882/api/image',
        type: "GET",
        success: function (data) {
            $('#testimg').attr('src', data);
            $('#testimg').attr('style', 'display: block;');
        }
    });

HTML

<img id="testimg" src="#" alt="Get from webapi" style="display: none;" />

【讨论】:

  • 这仅在我创建 HttpRequest、设置授权标头然后获取媒体文件时才有效。我做不到,我正在渲染图像元素并将 src 设置为像 /download/{file_id} 这样的 URL。那么如何检查请求是否经过身份验证?因为在这种情况下没有用户上下文。当前登录标识是 WindowsIdentity。
猜你喜欢
  • 1970-01-01
  • 2015-04-25
  • 1970-01-01
  • 2016-10-06
  • 2013-05-05
  • 1970-01-01
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多