Startup.cs 6.35 KB
using System;
using System.IO;
using System.Reflection;
using Hh.Mes.Api.AOP;
using Hh.Mes.API.AOP;
using Hh.Mes.Common.config;
using Hh.Mes.Service.Repository;
using Hh.Mes.Service.SystemAuth;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;

namespace Hh.Mes.Api
{
    public class Startup
    {
        //1.1 设置可跨域
        private readonly string cors = "cors";//名字随便起

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            #region 自定义配置appsettings.json 节点 AppCustomSettings 使用方法:AppSettings.GetAppSeting("xxx")
            AppSettings.SetAppSetting(Configuration.GetSection("AppCustomSettings"));
            ConfigRead.GetInstance.GetAppsetConnection().AppCustomExtend1 = AppSettings.GetAppSeting("AppCustomExtend1");
            ConfigRead.GetInstance.GetAppsetConnection().AppCustomExtend2 = AppSettings.GetAppSeting("AppCustomExtend2");
            ConfigRead.GetInstance.GetAppsetConnection().AppCustomExtend3 = AppSettings.GetAppSeting("AppCustomExtend3");
            ConfigRead.GetInstance.GetAppsetConnection().AppCustomExtend4 = AppSettings.GetAppSeting("AppCustomExtend4");

            ConfigRead.GetInstance.GetAppsetConnection().AppCustomExtend5 = AppSettings.GetAppSeting("AppCustomExtend5");
            ConfigRead.GetInstance.GetAppsetConnection().AppCustomExtend6 = AppSettings.GetAppSeting("AppCustomExtend6");
            ConfigRead.GetInstance.GetAppsetConnection().AppCustomExtend7 = AppSettings.GetAppSeting("AppCustomExtend7");
            ConfigRead.GetInstance.GetAppsetConnection().AppCustomExtend8 = AppSettings.GetAppSeting("AppCustomExtend8");
            #endregion

            //https://www.cnblogs.com/puzi0315/p/13523420.html
            services.AddControllers().AddNewtonsoftJson();

            #region 注册数据库基础操作和工作单元 ,SqlSugars
            //SqlSugars
            services.BatchRegisterService(Program.service, Program.serviceSuffix);
            services.AddDirectoryBrowser();
            services.AddScoped(typeof(IAuth), typeof(LocalAuth));
            #endregion


            //在这里你已经拦截器FilterController注入到全局请求中
            services.AddControllers(option =>
            {
                //设置异常过滤器
                option.Filters.Add<AuthFilterAttribute>();
                option.Filters.Add<HttpGlobalExceptionFilter>();
            });

            services.AddControllers();

            #region  Swagger 步骤1  http://127.0.0.1:9008/swagger/index.html
            //services.AddSwaggerGen(c =>
            //{
            //    c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApi", Version = "v1", Description = $"Copyright {DateTime.Now.Year}{AppSettings.GetAppSeting("copyright")} " });
            //    // 获取xml文件名
            //    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
            //    // 获取xml文件路径
            //    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
            //    // 添加控制器层注释,true表示显示控制器注释
            //    c.IncludeXmlComments(xmlPath, true);
            //});
            #endregion

            //1.2 设置可跨域
            services.AddCors(options =>
            {
                options.AddPolicy(cors, builder => builder.AllowAnyOrigin()
                    .WithMethods("GET", "POST", "HEAD", "PUT", "DELETE", "OPTIONS"));
            });

            //System.InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor' while attempting to activate 
            services.AddHttpContextAccessor();

            //Asp.Net Core获取请求上下文HttpContext https://www.cnblogs.com/tianma3798/p/10361644.html
            services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();

            #region 注入登录、授权等服务
            services.AddScoped<LoginParse>();
            services.AddScoped<AuthContextFactory>();
            services.AddScoped<SystemAuthStrategy>();
            services.AddScoped<NormalAuthStrategy>();
            services.AddScoped(typeof(IAuth), typeof(LocalAuth));
            #endregion
 
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            #region Swagger 步骤2 
            //app.UseSwagger();
            //app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebApi v1"));
            #endregion

            #region 解决Ubuntu Nginx 代理不能获取IP问题
            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            });
            #endregion

            #region  开启静态资源访问  https://blog.csdn.net/lzlawy1314/article/details/112061650
            app.UseStaticFiles();
            string filePath = "UploadFile";
            string filepath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filePath);
            if (!Directory.Exists(filepath)) Directory.CreateDirectory(filepath);
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(filepath),
                RequestPath = "/" + filePath
            });
            #endregion

            //欢迎页 根据实际情况开启
            //app.UseWelcomePage("/");

            app.UseRouting();

            //1.3 设置可跨域
            app.UseCors(cors);

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute("api", "api/{controller}/{action}");
                endpoints.MapControllers();
            });
        }
    }
}