ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

.net core 中使用httpclient下载文件

2021-11-10 16:02:59  阅读:496  来源: 互联网

标签:core name httpClientFactory System services using net public httpclient


  1. services里添加如下
public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
            //services.AddSignalR();
            //services.AddDbContext<PostgreSqlDB>();
            services.AddHttpClient();
        }
  1. controller里注入IHttpClientFactory
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using SignalRAPI.Hubs;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace SignalRAPI.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class DownLoadController : ControllerBase
    {

        private IHttpClientFactory _httpClientFactory;
        public DownLoadController(IHubContext<ChatHub> HubContext,IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }


        
        [HttpPost]
        public async void DownLoadFromUrl([FromQuery] string url,string name)
        {
            if (!System.IO.File.Exists(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, name)))
            {
                var client = _httpClientFactory.CreateClient();
                byte[] fileBytes = await client.GetByteArrayAsync(url);
                System.IO.File.WriteAllBytes(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, name), fileBytes);
                _HubContext.Clients.All.SendAsync("download", name);
            }
            _HubContext.Clients.All.SendAsync("download", name);
        }
        // POST api/<DownLoadController>
        [HttpPost]
        public void Post([FromBody] string value)
        {

        }
    }
}

标签:core,name,httpClientFactory,System,services,using,net,public,httpclient
来源: https://blog.csdn.net/weixin_43632687/article/details/121250158

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有