ASP.NET Core:是否可以使用HttpClient来获取文件并直接返回? [英] ASP.NET Core: Is it possible to use HttpClient to fetch a file and return directly?

查看:501
本文介绍了ASP.NET Core:是否可以使用HttpClient来获取文件并直接返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个内部API,可以获取并返回文件结果.但是,此API没有任何身份验证/角色/权限检查的概念,因此无法进行修改.

I have an internal API that would fetch and return a fileresult. However, this API does not have any concept of authentication/role/permission checks and cannot be modified to do so.

我想在现有的ASP.NET Core 2 Web API上创建一个Web API终结点,以进行权限检查,对该内部API进行调用并将文件结果返回给Web客户端.

I would like to create an web API endpoint on an existing ASP.NET Core 2 Web API to do permission check, make a call to this internal API and return the fileresult back to a web client.

是否有可能使包装器API端点仅传递它获取的任何内容作为文件结果,而不必重建响应(例如,指定文件名,内容类型等)?文件可以是图像,pdf,文档.我希望此包装器API仅执行权限检查并使用某种fileId调用内部API端点,而无需了解内容的长度或类型.

Would it be possible to get the wrapper API endpoint to just pass whatever it fetches as a file result without having to reconstruct the response (e.g., specify file name, content type, etc)? The files could be images, pdfs, document. I would prefer that this wrapper API only do permission check and make a call to the internal API endpoint using some sort of fileId and not need to know about the content length or type.

推荐答案

按照@ chris-pratt的建议,事实并非如我最初预期的那样复杂地重建了结果.我最终以这种方式实施,以防有人需要在这里做类似的事情.

Per @chris-pratt's recommendation, turned out it wasn't that complicate to reconstruct the result as I originally anticipated. I ended up implementing this way in case someone needs to do something similar here.

... some validation logic outside the scope of the question...
using (HttpClient client = new HttpClient())
                {
                    var file = await client.GetAsync($"{someURL}/{id}");
                    return new FileContentResult(await file.Content.ReadAsByteArrayAsync(), file.Content.Headers.ContentType.MediaType);
                }

这篇关于ASP.NET Core:是否可以使用HttpClient来获取文件并直接返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆