微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 在验证时从web api控制器操作返回图像

我有一个Web api,它使用带有承载令牌的owin身份验证.我将同时拥有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;
}

这就是我在Web客户端上显示它的方式:

<img src="/api/Secure/GetFile" id="img" />

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

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

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

解决方法

我认为“使用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;" />

原文地址:https://www.jb51.cc/csharp/99122.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐