其他分享
首页 > 其他分享> > .net core 中使用httpclient下载文件

.net core 中使用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