Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从使用DMZ API的公共web API获取文件_C#_.net_Api_Web_Core - Fatal编程技术网

C# 从使用DMZ API的公共web API获取文件

C# 从使用DMZ API的公共web API获取文件,c#,.net,api,web,core,C#,.net,Api,Web,Core,我有两个API: 公共API DMZ中的API 我需要实现一个在公共API中返回文件的方法 DMZ中的API: public HttpResponseMessage GetContent(int id) { var content = from m in db.messagestoimages where m.Message == id select m; i

我有两个API:

  • 公共API
  • DMZ中的API
  • 我需要实现一个在公共API中返回文件的方法

    DMZ中的API:

        public HttpResponseMessage GetContent(int id)
        {
            var content = from m in db.messagestoimages
                          where m.Message == id
                          select m;
    
            if (content == null || content.Count() == 0)
            {
                return null;
            }
            string fileName = content.First().ImageURL;
    
            string fullPath = AppDomain.CurrentDomain.BaseDirectory  + fileName;
            if (File.Exists(fullPath))
            {
    
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                var fileStream = new FileStream(fullPath, FileMode.Open);
                response.Content = new StreamContent(fileStream);
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                response.Content.Headers.ContentDisposition.FileName = fileName;
                return response;
            }
    
            return null;
        }
    
    公共API

        public HttpResponseMessage Get(string id)
        {
            try
            {
                //if (form.file != null && form.file.Length > 0)
                {
                    using (var client = new HttpClient())
                    {
                        try
                        {
                            string host = configuration.GetSection("MySettings").GetSection("OctopusURL").Value;
    
                            client.BaseAddress = new Uri(host);
    
                            var response =  client.GetAsync("api/Content/" + id);
    
    
                            return response.Result;
    
                        }
                        catch (Exception ex)
                        {
                            return new HttpResponseMessage(HttpStatusCode.NotFound);
                        }
                    }
                }
    
            }
            catch (Exception ex)
            {
                return new HttpResponseMessage(HttpStatusCode.NotFound); // 500 is generic server error
            }
        }
    
    若我直接调用DMZ方法,文件下载成功。 如果我调用公共API,我不会得到一个文件。唯一内容

    {
        "version": {
            "major": 1,
            "minor": 1,
            "build": -1,
            "revision": -1,
            "majorRevision": -1,
            "minorRevision": -1
        },
        "content": {
            "headers": [
                {
                    "key": "Content-Length",
                    "value": [
                        "17488"
                    ]
                },
                {
                    "key": "Content-Type",
                    "value": [
                        "application/octet-stream"
                    ]
                },
                {
                    "key": "Expires",
                    "value": [
                        "-1"
                    ]
                },
                {
                    "key": "Content-Disposition",
                    "value": [
                        "attachment; filename=\"/Userimage/3A297B090A41B649BF80.jpeg\""
                    ]
                }
            ]
        },
        "statusCode": 200,
        "reasonPhrase": "OK",
        "headers": [
            {
                "key": "Cache-Control",
                "value": [
                    "no-cache"
                ]
            },
            {
                "key": "Pragma",
                "value": [
                    "no-cache"
                ]
            },
            {
                "key": "Server",
                "value": [
                    "Microsoft-IIS/10.0"
                ]
            },
            {
                "key": "X-AspNet-Version",
                "value": [
                    "4.0.30319"
                ]
            },
            {
                "key": "X-SourceFiles",
                "value": [
                    "=?UTF-8?B?QzpcVXNlcnNcbmFyaW1cc291cmNlXHJlcG9zXENoYXRBc3Npc3RlbnRcQ2hhdEFzc2lzdGFudFxDaGF0QXNzaXN0ZW50XGFwaVxDb250ZW50XDkzMjQ=?="
                ]
            },
            {
                "key": "X-Powered-By",
                "value": [
                    "ASP.NET"
                ]
            },
            {
                "key": "Date",
                "value": [
                    "Wed, 21 Aug 2019 13:43:26 GMT"
                ]
            }
        ],
        "requestMessage": {
            "version": {
                "major": 2,
                "minor": 0,
                "build": -1,
                "revision": -1,
                "majorRevision": -1,
                "minorRevision": -1
            },
            "content": null,
            "method": {
                "method": "GET"
            },
            "requestUri": "http://localhost:60236/api/Content/9324",
            "headers": [],
            "properties": {}
        },
        "isSuccessStatusCode": true
    }
    
    我怎样才能解决这个问题

    我尝试更改公共API,使其获得流、创建响应和返回,但效果不一样

                            string host = configuration.GetSection("MySettings").GetSection("OctopusURL").Value;
    
                            client.BaseAddress = new Uri(host);
    
                            var responseFromServer = await client.GetAsync("api/Images/" + id);
                            Stream streamToReadFrom = await responseFromServer.Content.ReadAsStreamAsync();
    
                            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                            response.Content = new StreamContent(streamToReadFrom);
                            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                            response.Content.Headers.ContentDisposition.FileName = "sd.jpg";
                            return response;      
    

    您应该使用公共API方法获取文件流,然后将其返回给客户端,与DMZ返回文件流的方式相同。

    经过测试,工作正常。 第一控制器:

    public class TestController : ApiController
    {
        [Route("GetContent")]
        public HttpResponseMessage Get()
        {
            string fileName = "a.json";
    
            string fullPath = AppDomain.CurrentDomain.BaseDirectory + fileName;
            if (File.Exists(fullPath))
            {
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                var fileStream = new FileStream(fullPath, FileMode.Open);
                response.Content = new StreamContent(fileStream);
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                response.Content.Headers.ContentDisposition.FileName = fileName;
                return response;
            }
    
            return null;
        }
    }
    
    public class PublicController : ApiController
    {
        [Route("GetContent")]
        public async Task<HttpResponseMessage> Get()
        {
            using (var client = new HttpClient())
            {
                try
                {
                    client.BaseAddress = new Uri("http://localhost:9000/");
    
                    var responseFromServer = await client.GetAsync("api/Test/GetContent");
                    Stream streamToReadFrom = await responseFromServer.Content.ReadAsStreamAsync();
    
                    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                    response.Content = new StreamContent(streamToReadFrom);
                    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                    response.Content.Headers.ContentDisposition.FileName = "sd.json";
                    return response;
    
                }
                catch (Exception ex)
                {
                    return new HttpResponseMessage(HttpStatusCode.NotFound);
                }
            }
        }
    }
    
    第二控制器:

    public class TestController : ApiController
    {
        [Route("GetContent")]
        public HttpResponseMessage Get()
        {
            string fileName = "a.json";
    
            string fullPath = AppDomain.CurrentDomain.BaseDirectory + fileName;
            if (File.Exists(fullPath))
            {
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                var fileStream = new FileStream(fullPath, FileMode.Open);
                response.Content = new StreamContent(fileStream);
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                response.Content.Headers.ContentDisposition.FileName = fileName;
                return response;
            }
    
            return null;
        }
    }
    
    public class PublicController : ApiController
    {
        [Route("GetContent")]
        public async Task<HttpResponseMessage> Get()
        {
            using (var client = new HttpClient())
            {
                try
                {
                    client.BaseAddress = new Uri("http://localhost:9000/");
    
                    var responseFromServer = await client.GetAsync("api/Test/GetContent");
                    Stream streamToReadFrom = await responseFromServer.Content.ReadAsStreamAsync();
    
                    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                    response.Content = new StreamContent(streamToReadFrom);
                    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                    response.Content.Headers.ContentDisposition.FileName = "sd.json";
                    return response;
    
                }
                catch (Exception ex)
                {
                    return new HttpResponseMessage(HttpStatusCode.NotFound);
                }
            }
        }
    }
    
    公共类PublicController:ApiController
    {
    [路线(“获取内容”)]
    公共异步任务Get()
    {
    使用(var client=new HttpClient())
    {
    尝试
    {
    client.BaseAddress=新Uri(“http://localhost:9000/");
    var responseFromServer=await client.GetAsync(“api/Test/GetContent”);
    streamToReadFrom=await responseFromServer.Content.ReadAsStreamAsync();
    HttpResponseMessage response=新的HttpResponseMessage(HttpStatusCode.OK);
    response.Content=新的StreamContent(streamToReadFrom);
    response.Content.Headers.ContentType=新的MediaTypeHeaderValue(“应用程序/八位字节流”);
    response.Content.Headers.ContentDisposition=新的ContentDispositionHeaderValue(“附件”);
    response.Content.Headers.ContentDisposition.FileName=“sd.json”;
    返回响应;
    }
    捕获(例外情况除外)
    {
    返回新的HttpResponseMessage(HttpStatusCode.NotFound);
    }
    }
    }
    }
    
    此对公共控制器方法的调用将下载文件:


    我试过了。请检查原始帖子,我在最后更新了。相同的结果。您是否尝试更改返回类型,以便可以返回
    返回文件(contentStream、content\u type、filename)?我刚刚更改为返回文件(streamToReadFrom,“jpg”,“test”);它返回InvalidOperationException:无法从返回类型为“Microsoft.AspNetCore.Mvc.FileStreamResult”的操作方法返回null。很抱歉,我将尝试调试它并查看流为null的原因。