Program.cs 6.94 KB
using Hh.Mes.Common.log;
using log4net;
using log4net.Config;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using System;
using System.IO;
using System.Linq;
using Hh.Mes.Common.config;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using Hh.Mes.API.Common;
using Hh.Mes.Common;

namespace Hh.Mes.Api
{
    /// <summary>
    /// 启动类  http or https监听 根据实际情况注释
    /// 注意:没有特殊情况请不要随便修改 lsw
    /// 路径 https://www.cnblogs.com/cang12138/p/5845122.html
    /// </summary>
    public class Program
    {
        #region 全局变量
        public static readonly string tokens = "Tokens";
        public static int httpsPort { get; set; }
        public static int httpPort { get; set; }

        /// <summary>
        /// 证书路径和密码
        /// </summary>
        public static string cerPath { get; set; }
        public static string cerPwd { get; set; }

        /// <summary>
        /// 运用程序key
        /// </summary>
        public static string AppKey { get; set; }
        public static string AppSecret { get; set; }

        public static readonly string service = "Hh.Mes.Service";
        public static readonly string serviceSuffix = "Service";
        #endregion

        public static void Main(string[] args)
        {
            ExceptionsHelp.Instance.ExecuteVoidFunc(() =>
            {
                #region Log4Net
                Log4NetHelper.Instance.Repository = LogManager.CreateRepository("NETCoreRepository");
                XmlConfigurator.Configure(Log4NetHelper.Instance.Repository, new FileInfo(Path.GetDirectoryName(typeof(Program).Assembly.Location) + "/Config/log4net.config"));
                #endregion

                #region 本地封装日接口日志
                Logging.GetInstance.InitWriteInterLog();
                #endregion

                InitSysValue();

                #region 端口是否占用

                if (httpsPort == 0 && httpPort == 0)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("HttpsPort、HttpsPort 端口配置都是0");
                    Console.ReadKey();
                    return;
                }

                if (httpsPort != 0)
                {
                    var isHttpsPort = ComputerHelp.PortInUse(httpsPort);
                    if (isHttpsPort)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("HttpsPort 端口已被占用:" + httpsPort);
                        Console.ReadKey();
                        return;
                    }
                }

                if (httpPort != 0)
                {
                    var isHttpPortk = ComputerHelp.PortInUse(httpPort);
                    if (isHttpPortk)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("HttpPort 端口已被占用:" + httpPort);
                        Console.ReadKey();
                        return;
                    }
                }
                #endregion

                CreateHostBuilder(args).Build().Run();
            });
        }

        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            X509Certificate2 certificate = null;
            if (httpsPort != 0) certificate = InitCer();
            Console.ResetColor();
            return Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseKestrel(options =>
                {
                    //跨域
                    options.AddServerHeader = false;

                    //https://www.cnblogs.com/lxhbky/p/11969478.html
                    //https://www.cnblogs.com/wucy/p/14824585.html
                    //设置Body大小限制256MB
                    options.Limits.MaxRequestBodySize = 268435456;

                    //https 根据实际情况开启监听
                    //options.Listen(IPAddress.Any, httpsPort, listenOptions =>
                    //{
                    //    listenOptions.UseHttps(certificate);
                    //});

                    //http 根据实际情况 开启监听
                    options.Listen(IPAddress.Any, httpPort);
                });
                webBuilder.UseStartup<Startup>();
                Console.WriteLine();
                Console.WriteLine("API接口程序 Init  Started successfully!");
                Console.WriteLine();
            });
        }

        private static void InitSysValue()
        {
            Console.Title = "海能发API接口 网关服务";
            #region 获取配置信息  
            httpPort = ConfigRead.GetInstance.GetAppsetConnection().HttpPort;
            httpsPort = ConfigRead.GetInstance.GetAppsetConnection().HttpsPort;


            //添加 json 文件路径
            var builder = new ConfigurationBuilder().SetBasePath(AppDomain.CurrentDomain.BaseDirectory).AddJsonFile("appsettings.json");
            //创建配置根对象
            var configurationRoot = builder.Build();
            //取 family 部分下的 mother 部分下的 name 部分
            var appCustomSettings = configurationRoot.GetSection("AppCustomSettings");
            AppKey = appCustomSettings.GetSection("AppKey").Value;
            AppSecret = appCustomSettings.GetSection("AppSecret").Value;
            #endregion

            Console.WriteLine("初始化值InitSysValue 成功!");
        }

        /// <summary>
        /// 证书 
        /// </summary>
        private static X509Certificate2 InitCer()
        {
            #region 证书
            var config = new ConfigurationBuilder().SetBasePath(AppContext.BaseDirectory)
                                          .AddEnvironmentVariables()
                                          .AddJsonFile("certificate.json", optional: true, reloadOnChange: true)
                                          .AddJsonFile($"certificate.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: true, reloadOnChange: true)
                                          .Build();

            //Log4NetHelper.Instance.Info("CreateHostBuilder方: Certificate path:" + AppContext.BaseDirectory);
            var certificateSettings = config.GetSection("certificateSettings");
            string certificateFileName = certificateSettings.GetValue<string>("filename");
            cerPwd = certificateSettings.GetValue<string>("password");
            cerPath = Path.Combine(AppContext.BaseDirectory, certificateFileName);
            if (!File.Exists(cerPath))
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine();
                Console.WriteLine("证书文件不存在!路径:" + cerPath);
                Console.ReadKey();
            }

            var certificate = new X509Certificate2(certificateFileName, cerPwd);
            Console.WriteLine("证书Cer,初始化读取配置成功!");
            return certificate;
            #endregion
        }
    }
}