.net core 中使用httpclient下载文件

  1. services里添加如下
public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
            //services.AddSignalR();
            //services.AddDbContext();
            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/
        [HttpPost]
        public void Post([FromBody] string value)
        {

        }
    }
}

你可能感兴趣的:(.netCore,C#,.netcore,mvc,microsoft)