.netCoreWebAPI中, 使用IHttpClientFactory 避免端口号被耗尽

using MyFrontCodeTest.Models;
using MyFrontCodeTest.Models.PLC;
using MyFrontCodeTest.Service;
using System.Net.Http;
using System.Text.Json;

namespace MyFrontCodeTest.Utils
{
    public class StartupInitializationService : IHostedService
    {
        private readonly MyS7Entry myS7Entry;
        private readonly IS7ConnService s7ConnService;
        private readonly ILogger<StartupInitializationService> logger;
        private readonly HttpClient httpClient;
        public StartupInitializationService(MyS7Entry myS7Entry
            , IS7ConnService s7ConnService
            , IHttpClientFactory httpClientFactory
            , ILogger<StartupInitializationService> logger
            )
        {
            this.myS7Entry = myS7Entry;
            this.s7ConnService = s7ConnService;
            this.logger = logger;
            this.httpClient = httpClientFactory.CreateClient();
        }
        public Task StartAsync(CancellationToken cancellationToken)
        {
            //try
            //{
            //    s7ConnService.ConnPlc();
            //}
            //catch (Exception ex)
            //{
            //    logger.LogError($"网络错误:{ex.Message}");
            //    return Task.CompletedTask;
            //}


            //myS7Entry.PropertyChanged += MyS7Entry_PropertyChanged;
            logger.LogWarning("初始化函数成功");

            myS7Entry.PropertyChanged += async (s, e) =>
            {
                if (e.PropertyName == "MyBool1")
                {
                    //目标服务器Api地址
                    string? url = "http://127.0.0.1:8881/endpoint/mes/kx/reportA";
                    Student stu = new()
                    {
                        Id = 1,
                        Name = "MyBool1",
                        Age = 999
                    };
                    var json = JsonSerializer.Serialize(stu);
                    var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
                    var response = await httpClient.PostAsync(url, content);
                    if (response.IsSuccessStatusCode)
                    {
                        logger.LogInformation("Data sent successfullyS1.");
                    }
                    else
                    {
                        logger.LogInformation("Failed to send dataS1.");
                    }
                }

                if (e.PropertyName == "MyShort2")
                {

                }
            };

            return Task.CompletedTask;
        }

        private void MyS7Entry_PropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "MyBool1")
            {

            }

            if (e.PropertyName == "MyBool2")
            {

            }
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            // 在应用程序停止时执行清理逻辑(如果有必要)
            return Task.CompletedTask;
        }
    }
}

builder.Services.AddHttpClient("testClient", (client) =>
{
    client.BaseAddress = new Uri("http://127.0.0.1:8889");
});

你可能感兴趣的:(.netcore)