You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
CoreShop/CoreCms.Net.Web.Admin/Startup.cs

284 lines
9.9 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using System;
using System.IO;
using System.Linq;
using Autofac;
using CoreCms.Net.Auth;
using CoreCms.Net.Configuration;
using CoreCms.Net.Core.AutoFac;
using CoreCms.Net.Core.Config;
using CoreCms.Net.Filter;
using CoreCms.Net.Loging;
using CoreCms.Net.Mapping;
using CoreCms.Net.Middlewares;
using CoreCms.Net.Services.Mediator;
using CoreCms.Net.Swagger;
using Essensoft.Paylink.Alipay;
using Essensoft.Paylink.WeChatPay;
using MediatR;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.DotNet.PlatformAbstractions;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Senparc.CO2NET;
using Senparc.CO2NET.AspNet;
using Senparc.Weixin;
using Senparc.Weixin.Entities;
using Senparc.Weixin.RegisterServices;
using Senparc.Weixin.WxOpen;
using SqlSugar;
namespace CoreCms.Net.Web.Admin
{
/// <summary>
/// Æô¶¯ÅäÖÃ
/// </summary>
public class Startup
{
/// <summary>
/// ¹¹Ô캯Êý
/// </summary>
/// <param name="configuration"></param>
/// <param name="env"></param>
public Startup(IConfiguration configuration, IWebHostEnvironment env)
{
Configuration = configuration;
Env = env;
}
/// <summary>
/// </summary>
public IConfiguration Configuration { get; }
/// <summary>
/// </summary>
public IWebHostEnvironment Env { get; }
/// <summary>
/// This method gets called by the runtime. Use this method to add services to the container.
/// </summary>
/// <param name="services"></param>
public void ConfigureServices(IServiceCollection services)
{
//Ìí¼Ó±¾µØ·¾¶»ñÈ¡Ö§³Ö
services.AddSingleton(new AppSettingsHelper(Env.ContentRootPath));
services.AddSingleton(new LogLockHelper(Env.ContentRootPath));
//Memory»º´æ
services.AddMemoryCacheSetup();
//Redis»º´æ
services.AddRedisCacheSetup();
//Ìí¼ÓÊý¾Ý¿âÁ¬½ÓSqlSugar×¢ÈëÖ§³Ö
services.AddSqlSugarSetup();
//ÅäÖÿçÓò£¨CORS£©
services.AddCorsSetup();
//Ìí¼ÓsessionÖ§³Ö(sessionÒÀÀµÓÚcache½øÐд洢)
services.AddSession();
// AutoMapperÖ§³Ö
services.AddAutoMapper(typeof(AutoMapperConfiguration));
//MediatR£¨Ö»ÐèҪע²áÒ»¸ö,ͬÏîÄ¿»òÀà¿âϾͲ»ÐèҪע²á¶à¸ö£©
services.AddMediatR(typeof(OrderPayedCommand).Assembly);
//ʹÓà SignalR
services.AddSignalR();
// ÒýÈëPayment ÒÀÀµ×¢Èë(Ö§¸¶±¦Ö§¸¶/΢ÐÅÖ§¸¶)
services.AddAlipay();
services.AddWeChatPay();
// ÔÚ appsettings.json ÖÐ ÅäÖÃÑ¡Ïî
services.Configure<WeChatPayOptions>(Configuration.GetSection("WeChatPay"));
services.Configure<AlipayOptions>(Configuration.GetSection("Alipay"));
//Swagger½Ó¿ÚÎĵµ×¢Èë
services.AddAdminSwaggerSetup();
//ÅäÖÃÒ×ÁªÔÆ´òÓ¡»ú
services.AddYiLianYunSetup();
//jwtÊÚȨ֧³Ö×¢Èë
services.AddAuthorizationSetupForAdmin();
//ÉÏÏÂÎÄ×¢Èë
services.AddHttpContextSetup();
//·þÎñÅäÖÃÖмÓÈëAutoFac¿ØÖÆÆ÷Ìæ»»¹æÔò¡£
services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>());
//΢ÐÅ×¢²á
services.AddSenparcWeixinServices(Configuration);
//×¢²ámvc£¬×¢²árazorÒýÇæÊÓͼ
services.AddMvc(options =>
{
//ʵÌåÑéÖ¤
options.Filters.Add<RequiredErrorForAdmin>();
//Òì³£´¦Àí
options.Filters.Add<GlobalExceptionsFilterForAdmin>();
//SwaggerÌÞ³ý²»ÐèÒª¼ÓÈëapiչʾµÄÁбí
options.Conventions.Add(new ApiExplorerIgnores());
options.EnableEndpointRouting = false;
})
.AddNewtonsoftJson(p =>
{
//Êý¾Ý¸ñʽÊ××ÖĸСд ²»Ê¹ÓÃÍÕ·å
p.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
//²»Ê¹ÓÃÍÕ·åÑùʽµÄkey
//p.SerializerSettings.ContractResolver = new DefaultContractResolver();
//ºöÂÔÑ­»·ÒýÓÃ
p.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
//ÉèÖÃʱ¼ä¸ñʽ
p.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
});
}
/// <summary>
/// Autofac¹æÔòÅäÖÃ
/// </summary>
/// <param name="builder"></param>
public void ConfigureContainer(ContainerBuilder builder)
{
builder.RegisterModule(new AutofacModuleRegister());
//»ñÈ¡ËùÓпØÖÆÆ÷ÀàÐͲ¢Ê¹ÓÃÊôÐÔ×¢Èë
var controllerBaseType = typeof(ControllerBase);
builder.RegisterAssemblyTypes(typeof(Program).Assembly)
.Where(t => controllerBaseType.IsAssignableFrom(t) && t != controllerBaseType)
.PropertiesAutowired();
}
/// <summary>
/// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
/// </summary>
/// <param name="app"></param>
/// <param name="env"></param>
/// <param name="senparcSetting"></param>
/// <param name="senparcWeixinSetting"></param>
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IOptions<SenparcSetting> senparcSetting,
IOptions<SenparcWeixinSetting> senparcWeixinSetting)
{
// ¼Ç¼ÇëÇóÓë·µ»ØÊý¾Ý (×¢Ò⿪ÆôȨÏÞ£¬²»È»±¾µØÎÞ·¨Ð´Èë)
app.UseReuestResponseLog();
// Óû§·ÃÎʼǼ(±ØÐë·Åµ½Íâ²ã£¬²»È»Èç¹ûÓöµ½Òì³££¬»á±¨´í£¬ÒòΪ²»ÄÜ·µ»ØÁ÷)(×¢Ò⿪ÆôȨÏÞ£¬²»È»±¾µØÎÞ·¨Ð´Èë)
app.UseRecordAccessLogsMildd();
// ¼Ç¼ipÇëÇó (×¢Ò⿪ÆôȨÏÞ£¬²»È»±¾µØÎÞ·¨Ð´Èë)
app.UseIpLogMildd();
// signalr
app.UseSignalRSendMildd();
app.UseSwagger().UseSwaggerUI(c =>
{
//¸ù¾Ý°æ±¾Ãû³Æµ¹Ðò ±éÀúչʾ
typeof(CustomApiVersion.ApiVersions).GetEnumNames().OrderByDescending(e => e).ToList().ForEach(
version =>
{
c.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"Doc {version}");
});
c.RoutePrefix = "doc";
});
#region Ê¢ÅÉ΢ÐÅ×¢²á
// Æô¶¯ CO2NET È«¾Ö×¢²á£¬±ØÐ룡
var registerService = app.UseSenparcGlobal(env, senparcSetting.Value, globalRegister =>
{
#region CO2NET È«¾ÖÅäÖÃ
#endregion
}, true)
//ʹÓà Senparc.Weixin SDK
.UseSenparcWeixin(senparcWeixinSetting.Value, weixinRegister =>
{
#region ΢ÐÅÏà¹ØÅäÖÃ
/* ΢ÐÅÅäÖÿªÊ¼
*
* ½¨Òé°´ÕÕÒÔÏÂ˳Ðò½øÐÐ×¢²á£¬ÓÈÆäÐ뽫»º´æ·ÅÔÚµÚһλ£¡
*/
#region ×¢²á¹«ÖںŻòС³ÌÐò£¨°´Ð裩
weixinRegister
//×¢²á¹«ÖÚºÅ
//.RegisterMpAccount(senparcWeixinSetting.Value, "¹«ÖÚºÅ")
//×¢²á¶à¸ö¹«ÖںŻòС³ÌÐò
.RegisterWxOpenAccount(senparcWeixinSetting.Value, "С³ÌÐò")
//AccessTokenContainer.Register(appId, appSecret, name);//ÃüÃû¿Õ¼ä£ºSenparc.Weixin.MP.Containers
#endregion
;
/* ΢ÐÅÅäÖýáÊø */
#endregion
});
#endregion
//ʹÓà Session
app.UseSession();
if (env.IsDevelopment())
{
// ÔÚ¿ª·¢»·¾³ÖУ¬Ê¹ÓÃÒì³£Ò³Ã棬ÕâÑù¿ÉÒÔ±©Â¶´íÎó¶ÑÕ»ÐÅÏ¢£¬ËùÒÔ²»Òª·ÅÔÚÉú²ú»·¾³¡£
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
// CORS¿çÓò
app.UseCors(AppSettingsConstVars.CorsPolicyName);
// Ìøתhttps
//app.UseHttpsRedirection();
// ʹÓþ²Ì¬Îļþ
app.UseStaticFiles();
// ʹÓÃcookie
app.UseCookiePolicy();
// ·µ»Ø´íÎóÂë
app.UseStatusCodePages();
// Routing
app.UseRouting();
// ÏÈ¿ªÆôÈÏÖ¤
app.UseAuthentication();
// È»ºóÊÇÊÚȨÖмä¼þ
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
"areas",
"{area:exists}/{controller=Default}/{action=Index}/{id?}"
);
endpoints.MapControllerRoute(
"default",
"{controller=Home}/{action=Index}/{id?}");
});
//ÉèÖÃĬÈÏÆðʼҳ£¨Èçdefault.html£©
//´Ë´¦µÄ·¾¶ÊÇÏà¶ÔÓÚwwwrootÎļþ¼ÐµÄÏà¶Ô·¾¶
var defaultFilesOptions = new DefaultFilesOptions();
defaultFilesOptions.DefaultFileNames.Clear();
defaultFilesOptions.DefaultFileNames.Add("index.html");
app.UseDefaultFiles(defaultFilesOptions);
app.UseStaticFiles();
}
}
}