c# - 通过身份验证时从 Web API Controller 操作返回图像

标签 c# jquery asp.net-web-api asp.net-web-api2 owin

我有一个使用不记名 token 的 owin 身份验证的 Web api。我将同时拥有 web 和 wpf (vb) 客户端,它们需要在经过身份验证时从 api 请求图像文件。未经身份验证的请求不应返回图像。

到目前为止,我有一个在未经过身份验证的情况下返回图像的有效解决方案:

我在 C# 中的 Controller 操作:

//[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 请求上没有访问 token 。

我可以使用 jQuery 通过 ajax 获取 GET,但我不知道如何将结果设置到 img 元素中。

如何为调用 img src 中的操作的 http GET 请求设置访问 token ,或将图像内容设置到 jQuery 中的 img 元素中?或者是否有更好的方法来完全做到这一点?

最佳答案

我认为“使用 jQuery 通过 ajax 获取 GET”会起作用。我们可以将 token 设置到请求 header 中。您可以尝试以下 api Controller 代码:

        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 片段

    $.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;" />

关于c# - 通过身份验证时从 Web API Controller 操作返回图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31185949/

相关文章:

c# - Asp.Net Identity : Web Api request fails authorization, 返回 200 OK

c# - 如何为非数据库操作实现类似事务的行为?

c# - 我可以通过 Telegram Bot API 通过用户 ID 获取电话号码吗?

javascript - jQuery 工具滚动宽度 100%

asp.net - 如何传递日期时间参数?

javascript - 是否可以从父窗口绑定(bind)到子窗口上的事件?

c# - 条件属性如何在幕后工作

c# - DataContext.Refresh() 的正确用法是什么?

javascript - JQuery DataTable 和 JsonDate,非常基础

php - 使用 jquery + <audio> w/php/mysql 循环播放时间