public class Startup
{
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)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddSenparcGlobalServices(Configuration)//Senparc.CO2NET 全局注册
.AddSenparcWeixinServices(Configuration);//Senparc.Weixin 注册
services.Configure<SenparcWeixinSetting>(Configuration.GetSection("SenparcWeixinSetting"));
services.AddTransient<IWeChatApplyCodeService, WeChatApplyCodeService>();
services.AddMemoryCache();
services.AddSingleton<IMemoryCache>(factory =>
{
var cache = new MemoryCache(new MemoryCacheOptions());
return cache;
});
services.AddSingleton<ICacheService, MemoryCacheService>();
services.AddCors(options =>
{
options.AddPolicy("any", builder =>
{
builder.AllowAnyOrigin() //允许任何来源的主机访问
//builder.WithOrigins("http://localhost:8080") ////允许http://localhost:8080的主机访问
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();//指定处理cookie
});
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IOptions<SenparcSetting> senparcSetting, IOptions<SenparcWeixinSetting> senparcWeixinSetting)
{
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();
}
app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());//跨域支持
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
IRegisterService register = RegisterService.Start(env, senparcSetting.Value).UseSenparcGlobal();// 启动 CO2NET 全局注册,必须!
register.UseSenparcWeixin(senparcWeixinSetting.Value, senparcSetting.Value);//微信全局注册,必须!
//定义ComponentVerifyTicketFunc
Func<string, string> getComponentVerifyTicketFunc = componentAppId =>
{
var dir = Path.Combine(Environment.CurrentDirectory + @"/App_Data/OpenTicket");
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
var file = Path.Combine(dir, string.Format("{0}.txt", componentAppId));
using (var fs = new FileStream(file, FileMode.Open))
{
using (var sr = new StreamReader(fs))
{
var ticket = sr.ReadToEnd();
return ticket;
}
}
};
//定义getAuthorizerRefreshTokenFunc
Func<string,string, string> getAuthorizerRefreshTokenFunc = (componentAppId, auhtorizerId) =>
{
var dir = Path.Combine(Environment.CurrentDirectory + @"/App_Data/AuthorizerInfo/"+ componentAppId);
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
var file = Path.Combine(dir, string.Format("{0}.bin", auhtorizerId));
if (!File.Exists(file))
{
return null;
}
using (Stream fs = new FileStream(file, FileMode.Open))
{
var binFormat = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
var result = (RefreshAuthorizerTokenResult)binFormat.Deserialize(fs);
return result.authorizer_refresh_token;
}
};
//定义authorizerTokenRefreshedFunc
Action<string, string, RefreshAuthorizerTokenResult> authorizerTokenRefreshedFunc = (componentAppId, auhtorizerId, refreshResult) =>
{
var dir = Path.Combine(Environment.CurrentDirectory + @"/App_Data/AuthorizerInfo/" + componentAppId);
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
var file = Path.Combine(dir, string.Format("{0}.bin", auhtorizerId));
using (Stream fs = new FileStream(file, FileMode.Create))
{
//这里存了整个对象,实际上只存RefreshToken也可以,有了RefreshToken就能刷新到最新的AccessToken
var binFormat = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
binFormat.Serialize(fs, refreshResult);
fs.Flush();
}
};
//全局只需注册一次
ComponentContainer.Register(senparcWeixinSetting.Value.Component_Appid, senparcWeixinSetting.Value.Component_Secret, getComponentVerifyTicketFunc, getAuthorizerRefreshTokenFunc, authorizerTokenRefreshedFunc);
}
}