通过身份验证时从web api控制器操作返回图像

时间:2015-07-02 13:28:09

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

我有一个使用带有承载令牌的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" />

这很好,但是当我在上面的操作中取消注释authorize属性时,图像文件没有显示,我收到一条401(未授权)消息,要求GET消息调用GetFile操作。这是因为GET请求中没有访问令牌。

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

如何在img src中为调用动作的http GET请求设置访问令牌,或者在jQuery中将图像内容设置为img元素?或者有更好的方法来完成这项工作吗?

1 个答案:

答案 0 :(得分:6)

我认为“使用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代码段

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