加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 07:40:54 所属栏目:百科 来源:网络整理
导读:我有一个Web api,它使用带有承载令牌的owin身份验证.我将同时拥有web和wpf(vb)客户端,这些客户端需要在验证时从api请求图像文件.不应在未经身份验证的请求上返回图像. 到目前为止,我有一个工作解决方案,在未经过身份验证时返回图像: 我在c#中的控制器操作:
我有一个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;" />

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读