zhaojs
2023-09-15 fc13938ff90213060532d99a600dea4a84456885
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
using AutoMapper;
using CommonUtil;
using EasyCaching.Core;
using EasyCaching.InMemory;
using Link.Api.Filters;
using Link.Common;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Steeltoe.Discovery.Client;
using Swashbuckle.AspNetCore.Swagger;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
 
namespace Link.Api
{
    /// <summary>
    /// 
    /// </summary>
    public class Startup
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="configuration"></param>
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
 
        /// <summary>
        /// 
        /// </summary>
        public IConfiguration Configuration { get; }
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
 
            services.AddMvc(options =>
            {
                //添加异常过滤捕捉
                options.Filters.Add<ExceptionFilter>();
                //添加操作进行前后过滤
                options.Filters.Add<ActionFilter>();
 
            });
 
            //配置Json输出格式
            services.AddMvc().AddJsonOptions(options =>
            {
                options.SerializerSettings.DateFormatString = Constants.DATE_TIME_FORMAT;
                options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Include;
            }
            );
 
            //配置Swagger生成服务
            //services.AddSwaggerGen(c =>
            //{
            //    //配置Swagger头部认证说明
            //    c.SwaggerDoc(Constants.SWAGGER_NAME, new Info()
            //    {
            //        Version = Constants.SWAGGER_VERSION,
            //        Title = Constants.SWAGGER_TITLE,
            //    });
 
 
            //    //配置Swagger读取的xml文件注释文档
            //    var file = System.IO.Directory.EnumerateFiles(AppContext.BaseDirectory, Constants.XML_SEARCH_PATTERN).GetEnumerator();
 
            //    while (file.MoveNext())
            //    {
            //        c.IncludeXmlComments(file.Current, true);
            //    }
            //}
            //);
 
            //注册业务服务
            var bizServiceDictionary = AssemblyLoad(Constants.SERVICE_LIBRARY_NAME);
            var bizServiceEnumerator = bizServiceDictionary.GetEnumerator();
            while (bizServiceEnumerator.MoveNext())
            {
                var biz = bizServiceEnumerator.Current;
 
                services.AddTransient(biz.Value, biz.Key);
            }
            //注册AutoMapper映射服务
            services.AddAutoMapper();
 
            services.AddEasyCaching(option =>
            {
                // use memory cache with a simple way
                option.UseInMemory(Constants.EASY_CACHE_MEMORY_DEFAULT_NAME);
            });
        }
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                //生产环境下,异常进行捕捉
                app.UseExceptionHandler(options =>
                {
                    options.Run(
                    async context =>
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                        context.Response.ContentType = TopConstants.CONTENT_TYPE_TEXT_HTML;
                        var ex = context.Features.Get<IExceptionHandlerFeature>();
                        if (ex != null)
                        {
                            string err = $"<h1>HttpStatusCode:{context.Response.StatusCode}</h1><h1>Error: {ex.Error.Message}</h1>{ex.Error.StackTrace}";
                            await context.Response.WriteAsync(err).ConfigureAwait(false);
                        }
                    });
                });
            }
           
            //启用Swagger
            //app.UseSwagger();
            ////启用SwaggerUI
            //app.UseSwaggerUI(c =>
            //{
            //    c.SwaggerEndpoint(Constants.SWAGGER_JSON_URL, Constants.API_LIBRARY_NAME);
            //}
            //);
 
            app.UseMvc();
            
        }
 
        /// <summary>
        /// Welcome
        /// </summary>
        /// <returns></returns>
        private string Welcome()
        {
            var builder = new StringBuilder();
            builder.AppendLine("Initializing ...");
            builder.AppendLine();
            builder.AppendLine("***************************************************************");
            builder.AppendLine("*                                                             *");
            builder.AppendLine("*                  Welcome To DuoMai.Link                     *");
            builder.AppendLine("*                                                             *");
            builder.AppendLine("***************************************************************");
            builder.AppendLine();
            builder.AppendLine("Start Success ^_^");
            return builder.ToString();
        }
 
        /// <summary>  
        /// 获取程序集中的实现类对应的多个接口
        /// </summary>  
        /// <param name="assemblyName">程序集</param>
        private Dictionary<Type, Type> AssemblyLoad(string assemblyName)
        {
            Assembly assembly = Assembly.Load(assemblyName);
            IEnumerable<Type> typeEnumerable = assembly.ExportedTypes;
 
            //排除基类服务
            IEnumerator<Type> typeEnumerator = typeEnumerable.Where(j => j.IsPublic && j.IsClass && !j.IsAbstract).GetEnumerator();
 
            Dictionary<Type, Type> result = new Dictionary<Type, Type>();
 
            while (typeEnumerator.MoveNext())
            {
                Type implementType = typeEnumerator.Current;
 
                Type interfaceType = implementType.GetInterfaces().First(j => j.Namespace == Constants.ISERVICE_LIBRARY_NAME);
 
                if (!result.ContainsKey(implementType))
                {
                    result.Add(implementType, interfaceType);
                }
            }
 
            return result;
        }
    }
}