public Startup(IConfiguration configuration, IHostingEnvironment env) { GlobalTo.Configuration = configuration; GlobalTo.HostingEnvironment = env; #region 第三方登录(如果不用,请以最快的速度删了,^_^) QQConfig.APPID = GlobalTo.GetValue("OAuthLogin:QQ:APPID"); QQConfig.APPKey = GlobalTo.GetValue("OAuthLogin:QQ:APPKey"); QQConfig.Redirect_Uri = GlobalTo.GetValue("OAuthLogin:QQ:Redirect_Uri"); WeiboConfig.AppKey = GlobalTo.GetValue("OAuthLogin:Weibo:AppKey"); WeiboConfig.AppSecret = GlobalTo.GetValue("OAuthLogin:Weibo:AppSecret"); WeiboConfig.Redirect_Uri = GlobalTo.GetValue("OAuthLogin:Weibo:Redirect_Uri"); GitHubConfig.ClientID = GlobalTo.GetValue("OAuthLogin:GitHub:ClientID"); GitHubConfig.ClientSecret = GlobalTo.GetValue("OAuthLogin:GitHub:ClientSecret"); GitHubConfig.Redirect_Uri = GlobalTo.GetValue("OAuthLogin:GitHub:Redirect_Uri"); GitHubConfig.ApplicationName = GlobalTo.GetValue("OAuthLogin:GitHub:ApplicationName"); TaobaoConfig.AppKey = GlobalTo.GetValue("OAuthLogin:Taobao:AppKey"); TaobaoConfig.AppSecret = GlobalTo.GetValue("OAuthLogin:Taobao:AppSecret"); TaobaoConfig.Redirect_Uri = GlobalTo.GetValue("OAuthLogin:Taobao:Redirect_Uri"); MicroSoftConfig.ClientID = GlobalTo.GetValue("OAuthLogin:MicroSoft:ClientID"); MicroSoftConfig.ClientSecret = GlobalTo.GetValue("OAuthLogin:MicroSoft:ClientSecret"); MicroSoftConfig.Redirect_Uri = GlobalTo.GetValue("OAuthLogin:MicroSoft:Redirect_Uri"); #endregion //无创建,有忽略 using (var db = new ContextBase()) { //不存在创建,创建后返回true if (db.Database.EnsureCreated()) { //调用重置数据库(实际开发中,你可能不需要,或只初始化一些表数据) new Controllers.ToolController().ResetDataBase(); } } }
/// <summary> /// 备份数据库&上传腾讯云对象存储 /// </summary> public static ActionResultVM BackupDataBase() { var vm = new ActionResultVM(); try { var listMsg = new List <object>(); var kp = "Work:BackupDataBase:SQLServer:"; //执行命令 var cmd = GlobalTo.GetValue(kp + "cmd"); var rt = Core.CmdTo.Shell(cmd); listMsg.Add(rt.ToJObject()); //上传配置 string bucketName = GlobalTo.GetValue(kp + "upload:bucketName"); string remotePath = string.Format(GlobalTo.GetValue(kp + "upload:remotePath"), DateTime.Now.ToString("yyyyMMdd_HHmmss")); string localPath = GlobalTo.GetValue(kp + "upload:localPath"); int APPID = Convert.ToInt32(GlobalTo.GetValue("ApiKey:AccessCOS:APPID")); string SecretId = GlobalTo.GetValue("ApiKey:AccessCOS:SecretId"); string SecretKey = GlobalTo.GetValue("ApiKey:AccessCOS:SecretKey"); //上传 var cos = new CosCloud(APPID, SecretId, SecretKey, UrlType.HB); var cu = cos.UploadFile(bucketName, remotePath, localPath); listMsg.Add(cu.ToJObject()); vm.Set(ARTag.success); vm.data = listMsg; } catch (Exception ex) { vm.Set(ex); } return(vm); }
/// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews() /*.AddRazorRuntimeCompilation()*/; //开发时:安装该包可以动态修改视图 cshtml 页面,无需重新运行项目 //发布时:建议删除该包,会生成一堆“垃圾” //Install-Package Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation services.AddControllers().AddNewtonsoftJson(options => { //Action原样输出JSON options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver(); //日期格式化 options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss.fff"; }); //配置swagger services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "FileServer API", Version = "v1" }); "FileServer,Fast".Split(',').ToList().ForEach(x => { c.IncludeXmlComments(System.AppContext.BaseDirectory + "Netnr." + x + ".xml", true); }); }); //路由小写 services.AddRouting(options => options.LowercaseUrls = true); //配置上传文件大小限制(详细信息:FormOptions) services.Configure <FormOptions>(options => { options.MultipartBodyLengthLimit = GlobalTo.GetValue <int>("StaticResource:MaxSize") * 1024 * 1024; }); }
public void OnActionExecuting(ActionExecutingContext context) { bool isv = GlobalTo.GetValue <bool>("Common:MailValid"); if (!isv && context.HttpContext.User.Identity.IsAuthenticated) { var uinfo = new Application.UserAuthService(context.HttpContext).Get(); //已验证邮箱 using var db = ContextBaseFactory.CreateDbContext(); uinfo = db.UserInfo.Find(uinfo.UserId); if (uinfo.UserId == 1 || uinfo.UserMailValid == 1) { isv = true; } } if (!isv) { var url = "/home/valid"; context.Result = new RedirectResult(url); } }
public string AboutServerStatus() { string url = GlobalTo.GetValue("ServiceApi:ServiceInfo"); var hwr = Core.HttpTo.HWRequest(url); hwr.UserAgent = GlobalTo.GetValue("UserAgent"); var result = Core.HttpTo.Url(hwr); //处理敏感信息 var rj = result.ToJObject(); var removeNodes = "available_isos email ip_addresses node_ip ptr ssh_port ve_mac1".Split(" ").ToList(); foreach (var item in removeNodes) { if (rj.ContainsKey(item)) { rj.Remove(item); } } result = rj.ToJson(); return(result); }
public ActionResultVM GetAppList(int pageNumber = 1, int pageSize = 20) { var vm = new ActionResultVM(); try { if (GlobalTo.GetValue <bool>("Safe:IsDev")) { vm = FileServerService.GetAppList(pageNumber, pageSize); } else { vm.Set(ARTag.refuse); } } catch (Exception ex) { vm.Set(ex); Core.ConsoleTo.Log(ex); } return(vm); }
/// <summary> /// 构建静态文件 /// </summary> /// <returns></returns> public ActionResultVM Index() { var vm = new ActionResultVM(); //设置是构建访问 var cacheKey = GlobalTo.GetValue("Common:BuildHtmlKey"); Core.CacheTo.Set(cacheKey, true); try { var urlPrefix = $"{Request.Scheme}://{Request.Host}/home/"; var path = GlobalTo.WebRootPath + "/"; //反射action var type = typeof(HomeController); var methods = type.GetMethods().Where(x => x.DeclaringType == type).ToList(); //并行请求 Parallel.ForEach(methods, mh => { string html = Core.HttpTo.Get(urlPrefix + mh.Name); Core.FileTo.WriteText(html, path + mh.Name.ToLower() + ".html", false); }); vm.Set(ARTag.success); vm.Data = "Count:" + methods.Count; } catch (Exception ex) { vm.Set(ex); } Core.CacheTo.Remove(cacheKey); return(vm); }
public ActionResultVM CreateApp(string password, string owner) { var vm = new ActionResultVM(); try { if (!Fast.ParsingTo.IsLinkPath(owner)) { vm.Msg = "owner 必填,仅为字母、数字"; } else if (owner.ToLower() == GlobalTo.GetValue("StaticResource:TmpDir").ToLower()) { vm.Msg = "owner 与临时目录冲突"; } else if (string.IsNullOrWhiteSpace(password) || password != GlobalTo.GetValue("Safe:AdminPassword")) { vm.Set(ARTag.unauthorized); vm.Msg = "密码错误或已关闭管理接口"; } else { vm = FileServerService.CreateApp(owner); if (vm.Code == -1 && vm.Msg.Contains("UNIQUE")) { vm.Set(ARTag.exist); vm.Msg = "owner 用户已经存在"; } } } catch (Exception ex) { vm.Set(ex); Core.ConsoleTo.Log(ex); } return(vm); }
/// <summary> /// 备份数据库 /// </summary> public static ActionResultVM BackupDataBase() { var vm = new ActionResultVM(); try { var listMsg = new List <object>(); var kp = "Work:BackupDataBase:SQLServer:"; if (GlobalTo.GetValue <bool>(kp + "enable") == true) { //执行命令 using var db = new ContextBase(); using var conn = db.Database.GetDbConnection(); conn.Open(); var connCmd = conn.CreateCommand(); connCmd.CommandText = GlobalTo.GetValue(kp + "cmd"); int en = connCmd.ExecuteNonQuery(); listMsg.Add(en); vm.Set(ARTag.success); vm.Data = listMsg; } else { vm.Set(ARTag.lack); } } catch (Exception ex) { vm.Set(ex); } return(vm); }
public static Logging.LoggingModel GetLog(Microsoft.AspNetCore.Http.HttpContext context) { string reqPath = context.Request.Path.ToString(); string reqQueryString = context.Request.QueryString.ToString(); //客户端信息 var ct = new Fast.ClientTo(context); //用户信息 var userinfo = new Application.UserAuthService(context).Get(); //日志保存 var mo = new Logging.LoggingModel() { LogApp = GlobalTo.GetValue("Common:EnglishName"), LogUid = userinfo?.UserName, LogNickname = userinfo?.Nickname, LogAction = reqPath, LogUrl = reqPath + reqQueryString, LogIp = ct.IPv4, LogReferer = ct.Referer, LogCreateTime = DateTime.Now, LogUserAgent = ct.UserAgent, LogGroup = "1", LogLevel = "I" }; var ddk = reqPath.ToLower().TrimStart('/'); if (DicDescription.ContainsKey(ddk)) { mo.LogContent = DicDescription[ddk]; } return(mo); }
/// <summary> /// 验证Token /// </summary> /// <param name="token"></param> /// <returns></returns> public static LoginUserVM TokenValid(string token) { LoginUserVM mo = null; try { if (!string.IsNullOrWhiteSpace(token)) { var key = GlobalTo.GetValue("VerifyCode:Key"); var jo = CalcTo.AESDecrypt(token, key).ToJObject(); if (DateTime.Now.ToTimestamp() < long.Parse(jo["expired"].ToString())) { mo = jo["mo"].ToString().ToEntity <LoginUserVM>(); } } } catch (Exception) { } return(mo); }
public ActionResultVM GetAppList(string password, int pageNumber = 1, int pageSize = 20) { var vm = new ActionResultVM(); try { if (string.IsNullOrWhiteSpace(password) || password != GlobalTo.GetValue("Safe:AdminPassword")) { vm.Set(ARTag.unauthorized); vm.Msg = "密码错误或已关闭管理接口"; } else { vm = FileServerService.GetAppList(pageNumber, pageSize); } } catch (Exception ex) { vm.Set(ex); Core.ConsoleTo.Log(ex); } return(vm); }
public ActionResultVM ResetAll(string password) { var vm = new ActionResultVM(); try { if (string.IsNullOrWhiteSpace(password) || password != GlobalTo.GetValue("Safe:AdminPassword")) { vm.Set(ARTag.unauthorized); vm.Msg = "密码错误或已关闭管理接口"; } else { //清空数据库 using var db = new SQLite.SQLiteConnection(FileServerService.SQLiteConn); db.DeleteAll <SysApp>(); db.DeleteAll <FileRecord>(); //删除上传文件 var rootdir = Fast.PathTo.Combine(GlobalTo.WebRootPath, GlobalTo.GetValue("StaticResource:RootDir")); if (Directory.Exists(rootdir)) { Directory.Delete(rootdir, true); } vm.Set(ARTag.success); } } catch (Exception ex) { vm.Set(ex); Core.ConsoleTo.Log(ex); } return(vm); }
public Startup(IConfiguration configuration, IHostEnvironment env) { GlobalTo.Configuration = configuration; GlobalTo.HostEnvironment = env; //设置日志 Logging.LoggingTo.DbRoot = GlobalTo.GetValue("logs:path").Replace("~", GlobalTo.ContentRootPath); Logging.LoggingTo.CacheWriteCount = GlobalTo.GetValue <int>("logs:CacheWriteCount"); Logging.LoggingTo.CacheWriteSecond = GlobalTo.GetValue <int>("logs:CacheWriteSecond"); #region 第三方登录 QQConfig.APPID = GlobalTo.GetValue("OAuthLogin:QQ:APPID"); QQConfig.APPKey = GlobalTo.GetValue("OAuthLogin:QQ:APPKey"); QQConfig.Redirect_Uri = GlobalTo.GetValue("OAuthLogin:QQ:Redirect_Uri"); WeiboConfig.AppKey = GlobalTo.GetValue("OAuthLogin:Weibo:AppKey"); WeiboConfig.AppSecret = GlobalTo.GetValue("OAuthLogin:Weibo:AppSecret"); WeiboConfig.Redirect_Uri = GlobalTo.GetValue("OAuthLogin:Weibo:Redirect_Uri"); GitHubConfig.ClientID = GlobalTo.GetValue("OAuthLogin:GitHub:ClientID"); GitHubConfig.ClientSecret = GlobalTo.GetValue("OAuthLogin:GitHub:ClientSecret"); GitHubConfig.Redirect_Uri = GlobalTo.GetValue("OAuthLogin:GitHub:Redirect_Uri"); TaoBaoConfig.AppKey = GlobalTo.GetValue("OAuthLogin:TaoBao:AppKey"); TaoBaoConfig.AppSecret = GlobalTo.GetValue("OAuthLogin:TaoBao:AppSecret"); TaoBaoConfig.Redirect_Uri = GlobalTo.GetValue("OAuthLogin:TaoBao:Redirect_Uri"); MicroSoftConfig.ClientID = GlobalTo.GetValue("OAuthLogin:MicroSoft:ClientID"); MicroSoftConfig.ClientSecret = GlobalTo.GetValue("OAuthLogin:MicroSoft:ClientSecret"); MicroSoftConfig.Redirect_Uri = GlobalTo.GetValue("OAuthLogin:MicroSoft:Redirect_Uri"); DingTalkConfig.appId = GlobalTo.GetValue("OAuthLogin:DingTalk:AppId"); DingTalkConfig.appSecret = GlobalTo.GetValue("OAuthLogin:DingTalk:AppSecret"); DingTalkConfig.Redirect_Uri = GlobalTo.GetValue("OAuthLogin:DingTalk:Redirect_Uri"); #endregion }
/// <summary> /// 推送到Gitee /// </summary> /// <param name="content">内容 base64</param> /// <param name="path">路径</param> /// <param name="message"></param> /// <param name="token"></param> /// <param name="or"></param> /// <returns></returns> private static string PutGitee(string content, string path, string message = "m", string token = null, string or = null) { if (string.IsNullOrWhiteSpace(token)) { token = GlobalTo.GetValue("ApiKey:Gitee:GistToken"); } if (string.IsNullOrWhiteSpace(or)) { or = GlobalTo.GetValue("Work:BackupToGit:or"); } var listor = or.Split('/'); var owner = listor.First(); var repo = listor.Last(); var uri = $"https://gitee.com/api/v5/repos/{owner}/{repo}/contents/{path}"; var hwr = HttpTo.HWRequest(uri, "POST", Encoding.UTF8.GetBytes(new { access_token = token, message, content }.ToJson())); hwr.Headers.Set("Content-Type", "application/json"); var result = HttpTo.Url(hwr); return(result); }
/// <summary> /// 验证Token /// </summary> /// <param name="token"></param> /// <returns></returns> public static Domain.UserInfo TokenValid(string token) { Domain.UserInfo mo = null; try { if (!string.IsNullOrWhiteSpace(token)) { var key = GlobalTo.GetValue("VerifyCode:Key"); var jo = Core.CalcTo.DeDES(token, key).ToJObject(); if (DateTime.Now.ToTimestamp() < long.Parse(jo["expired"].ToString())) { mo = jo["mo"].ToString().ToEntity <Domain.UserInfo>(); } } } catch (Exception) { } return(mo); }
/// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddControllers().AddNewtonsoftJson(options => { //Actionԭ�����JSON options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver(); //���ڸ�ʽ�� options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; }); //����swagger services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "FileServer API", Version = "v1" }); "FileServer,Fast".Split(',').ToList().ForEach(x => { c.IncludeXmlComments(System.AppContext.BaseDirectory + "Blog." + x + ".xml", true); }); }); //·��Сд services.AddRouting(options => options.LowercaseUrls = true); //�����ϴ��ļ���С���ƣ���ϸ��Ϣ��FormOptions�� services.Configure <FormOptions>(options => { options.MultipartBodyLengthLimit = GlobalTo.GetValue <int>("StaticResource:MaxSize") * 1024 * 1024; }); }
/// <summary> /// 推送到GitHub /// </summary> /// <param name="content">内容 base64</param> /// <param name="path">路径</param> /// <param name="message"></param> /// <param name="token"></param> /// <param name="or"></param> /// <returns></returns> private static string PutGitHub(string content, string path, string message = "m", string token = null, string or = null) { if (string.IsNullOrWhiteSpace(token)) { token = GlobalTo.GetValue("ApiKey:GitHub:GistToken"); } if (string.IsNullOrWhiteSpace(or)) { or = GlobalTo.GetValue("Work:BackupToGit:or"); } var put = $"https://api.github.com/repos/{or}/contents/{path}"; var hwr = HttpTo.HWRequest(put, "PUT", Encoding.UTF8.GetBytes(new { message, content }.ToJson())); hwr.Headers.Set("Accept", "application/vnd.github.v3+json"); hwr.Headers.Set("Authorization", $"token {token}"); hwr.Headers.Set("Content-Type", "application/json"); hwr.UserAgent = "Netnr Agent"; var result = HttpTo.Url(hwr); return(result); }
/// <summary> /// 本地授权:被减数与当前小时、分钟分别求差,满足容错分钟数即有效的KEY /// /// 举例: /// 配置 小时被减数80,分钟被减数80,假定现在时间是 16:50 /// 那么对应的KEY是 80-16=64,80-50=30 即 6430 /// /// </summary> /// <param name="sk"></param> /// <returns></returns> public static bool LocalIsAuth(string sk) { bool b = false; if (sk.Length == 4) { try { //小时被减数,24小时制 int bh = GlobalTo.GetValue <int>("LocalAuth:BeHour"); //分钟被减数 int bm = GlobalTo.GetValue <int>("LocalAuth:BeMinute"); //容错分钟数 int rm = GlobalTo.GetValue <int>("LocalAuth:RangeMinute"); string h = (bh - Convert.ToInt32(sk.Substring(0, 2))).ToString().PadLeft(2, '0'); int mm = bm - Convert.ToInt32(sk.Substring(2)); string m = (Math.Min(mm, 59)).ToString().PadLeft(2, '0'); DateTime dtn = DateTime.Now; if (DateTime.TryParse(dtn.ToString("yyyy-MM-dd ") + h + ":" + m, out DateTime dta)) { //与当前时间容错分钟 if (dta >= dtn.AddMinutes(-rm) && dta <= dtn.AddMinutes(rm)) { b = true; } } } catch (Exception) { } } return(b); }
public override void OnActionExecuting(ActionExecutingContext context) { //日志 var hc = context.HttpContext; if (GlobalTo.GetValue <bool>("logs:enable") && string.IsNullOrWhiteSpace(hc.Request.Query["__nolog"].ToString())) { string controller = context.RouteData.Values["controller"].ToString().ToLower(); string action = context.RouteData.Values["action"].ToString().ToLower(); //日志保存 var mo = GetLog(context.HttpContext); mo.LogAction = controller + "/" + action; if (DicDescription.ContainsKey(mo.LogAction)) { mo.LogContent = DicDescription[mo.LogAction]; } Logging.LoggingTo.Add(mo); } base.OnActionExecuting(context); }
public ActionResultVM API98([FromForm] IFormCollection form, string cp = null) { var vm = new ActionResultVM(); try { var files = form.Files; if (files.Count > 0) { var file = files[0]; int maxsize = GlobalTo.GetValue <int>("APIOut:API98:MaxSize"); if (file.Length > 1024 * 1024 * maxsize) { vm.code = 1; vm.msg = maxsize + " MB max per file"; } else { var now = DateTime.Now; string filename = now.ToString("HHmmss") + Guid.NewGuid().ToString("N").Substring(25, 4); string ext = file.FileName.Substring(file.FileName.LastIndexOf('.')); if (ext.ToLower() == ".exe") { vm.code = 2; vm.msg = "Unsupported file format:" + ext; } else { //自定义路径 if (!string.IsNullOrWhiteSpace(cp)) { cp = cp.TrimStart('/').TrimEnd('/') + '/'; } var path = cp + now.ToString("yyyy/MM/dd/"); var rootdir = GlobalTo.WebRootPath + "/" + (GlobalTo.GetValue("APIOut:API98:RootDir").TrimStart('/').TrimEnd('/') + "/"); string fullpath = rootdir + path; if (!Directory.Exists(fullpath)) { Directory.CreateDirectory(fullpath); } using (var fs = new FileStream(fullpath + filename + ext, FileMode.CreateNew)) { file.CopyTo(fs); fs.Flush(); } var FilePath = path + filename + ext; var jo = new JObject { ["server"] = GlobalTo.GetValue("APIOut:API98:Server").TrimEnd('/') + '/', ["path"] = FilePath }; vm.data = jo; vm.Set(ARTag.success); } } } else { vm.Set(ARTag.lack); } } catch (Exception ex) { vm.Set(ex); Core.ConsoleTo.Log(ex); } return(vm); }
/// <summary> /// 验证 /// </summary> /// <returns></returns> public IActionResult Verify() { var vm = new ActionResultVM(); var id = RouteData.Values["id"]?.ToString().ToUpper(); if (!string.IsNullOrWhiteSpace(id)) { var uinfo = new UserAuthAid(HttpContext).Get(); switch (id.ToLower()) { //发送验证邮箱 case "send": { if (User.Identity.IsAuthenticated) { using var db = new ContextBase(); var usermo = db.UserInfo.Find(uinfo.UserId); if (usermo.UserMailValid == 1) { vm.msg = "邮箱已经完成验证"; } else if (string.IsNullOrWhiteSpace(usermo.UserMail)) { vm.msg = "邮箱不能为空"; } else { var cacheKey = "Global_VerifyMail_" + usermo.UserMail; var issend = CacheTo.Get(cacheKey) as bool?; if (issend == true) { vm.msg = "1分钟内只能发送一次验证信息"; } else { var tml = FileTo.ReadText(GlobalTo.WebRootPath + "/lib/mailchecker/", "list.txt"); if (tml.Contains(usermo.UserMail.Split('@').LastOrDefault())) { vm.msg = "该邮箱已被屏蔽"; } else { //发送验证 var ToMail = usermo.UserMail; var vjson = new { mail = ToMail, ts = DateTime.Now.ToTimestamp() }.ToJson(); var vcode = CalcTo.EnDES(vjson, GlobalTo.GetValue("VerifyCode:Key")).ToLower(); var VerifyLink = string.Format(GlobalTo.GetValue("VerifyCode:Url"), vcode); var txt = FileTo.ReadText(GlobalTo.WebRootPath + "/template/", "sendmailverify.html"); txt = txt.Replace("@ToMail@", ToMail).Replace("@VerifyLink@", VerifyLink); vm = MailAid.Send(ToMail, "验证你的邮箱", txt); if (vm.code == 200) { vm.msg = "已发送成功"; CacheTo.Set(cacheKey, true, 60, false); } } } } } else { vm.msg = "请登录"; } } break; //验证邮箱 default: try { var vjson = CalcTo.DeDES(id, GlobalTo.GetValue("VerifyCode:Key")).ToJObject(); if (DateTime.Now.ToTimestamp() - Convert.ToInt32(vjson["ts"]) < 60 * 5) { var mail = vjson["mail"].ToString(); if (string.IsNullOrWhiteSpace(mail)) { vm.msg = "邮件地址有误"; } else { using var db = new ContextBase(); var usermo = db.UserInfo.FirstOrDefault(x => x.UserMail == mail); if (usermo != null) { if (usermo.UserMailValid == 1) { vm.msg = "已验证,勿重复验证"; } else { usermo.UserMailValid = 1; db.UserInfo.Update(usermo); int num = db.SaveChanges(); vm.Set(num > 0); if (vm.code == 200) { vm.msg = "恭喜你,验证成功"; } } } else { vm.msg = "邮件地址无效"; } } } else { vm.msg = "链接已过期(5分钟内有效)"; } } catch (Exception) { vm.msg = "链接已失效"; } break; } } else { vm.msg = "缺失验证码信息"; } return(View(vm)); }
public ActionResultVM UpdateUserPhoto(string type, string source) { var vm = new ActionResultVM(); var uinfo = new UserAuthAid(HttpContext).Get(); try { var rootdir = GlobalTo.WebRootPath + "/" + (GlobalTo.GetValue("StaticResource:RootDir").TrimStart('/').TrimEnd('/') + "/"); var path = GlobalTo.GetValue("StaticResource:AvatarPath").TrimEnd('/').TrimStart('/') + '/'; var fullpath = rootdir + path; if (!Directory.Exists(fullpath)) { Directory.CreateDirectory(fullpath); } if (string.IsNullOrWhiteSpace(uinfo.UserPhoto)) { uinfo.UserPhoto = UniqueTo.LongId() + ".jpg"; } var upname = uinfo.UserPhoto.Split('?')[0]; var npnew = upname + "?" + DateTime.Now.ToTimestamp(); switch (type) { case "file": { source = source.Substring(source.LastIndexOf(",") + 1); byte[] bytes = Convert.FromBase64String(source); using var ms = new MemoryStream(bytes); using var bmp = new System.Drawing.Bitmap(ms); var hp = fullpath + upname.Replace(".", "_lg."); bmp.Save(hp, ImageFormat.Jpeg); ImageTo.MinImg(hp, fullpath, upname, 40, 40, "wh"); using (var db = new ContextBase()) { var usermo = db.UserInfo.Find(uinfo.UserId); usermo.UserPhoto = npnew; db.UserInfo.Update(usermo); int num = db.SaveChanges(); if (num > 0) { using var ac = new AccountController(); ac.SetAuth(HttpContext, usermo); } } vm.Set(ARTag.success); } break; case "link": { using var wc = new System.Net.WebClient(); var hp = fullpath + upname.Replace(".", "_lg."); wc.DownloadFile(source, hp); ImageTo.MinImg(hp, fullpath, upname, 40, 40, "wh"); using (var db = new ContextBase()) { var usermo = db.UserInfo.Find(uinfo.UserId); usermo.UserPhoto = npnew; db.UserInfo.Update(usermo); int num = db.SaveChanges(); if (num > 0) { using var ac = new AccountController(); ac.SetAuth(HttpContext, usermo); } } vm.Set(ARTag.success); } break; } } catch (Exception ex) { vm.Set(ex); } return(vm); }
public IActionResult AuthCallback(LoginBase.AuthorizeResult authorizeResult) { var vm = new ActionResultVM(); try { if (string.IsNullOrWhiteSpace(authorizeResult.code)) { vm.Set(ARTag.unauthorized); } else { //唯一标示 string openId = string.Empty; //注册信息 var mo = new Domain.UserInfo() { LoginLimit = 0, UserSex = 0, UserCreateTime = DateTime.Now }; //头像 string avatar = string.Empty; //头像(高清) string avatarhd = string.Empty; Enum.TryParse(RouteData.Values["id"]?.ToString(), true, out ValidateloginType vtype); switch (vtype) { case ValidateloginType.qq: { //获取 access_token var tokenEntity = QQ.AccessToken(new QQ_AccessToken_RequestEntity() { code = authorizeResult.code }); //获取 OpendId var openidEntity = QQ.OpenId(new QQ_OpenId_RequestEntity() { access_token = tokenEntity.access_token }); //获取 UserInfo var userEntity = QQ.OpenId_Get_User_Info(new QQ_OpenAPI_RequestEntity() { access_token = tokenEntity.access_token, openid = openidEntity.openid }); //身份唯一标识 openId = openidEntity.openid; mo.OpenId1 = openId; mo.Nickname = userEntity.nickname; mo.UserSex = userEntity.gender == "男" ? 1 : 2; mo.UserSay = ""; mo.UserUrl = ""; avatar = userEntity.figureurl_qq_1; avatarhd = userEntity.figureurl_qq_2; } break; case ValidateloginType.weibo: { //获取 access_token var tokenEntity = Weibo.AccessToken(new Weibo_AccessToken_RequestEntity() { code = authorizeResult.code }); //获取 access_token 的授权信息 var tokenInfoEntity = Weibo.GetTokenInfo(new Weibo_GetTokenInfo_RequestEntity() { access_token = tokenEntity.access_token }); //获取 users/show var userEntity = Weibo.UserShow(new Weibo_UserShow_RequestEntity() { access_token = tokenEntity.access_token, uid = Convert.ToInt64(tokenInfoEntity.uid) }); openId = tokenEntity.access_token; mo.OpenId2 = openId; mo.Nickname = userEntity.screen_name; mo.UserSex = userEntity.gender == "m" ? 1 : userEntity.gender == "f" ? 2 : 0; mo.UserSay = userEntity.description; mo.UserUrl = userEntity.domain; avatar = userEntity.profile_image_url; avatarhd = userEntity.avatar_large; } break; case ValidateloginType.github: { //获取 access_token var tokenEntity = GitHub.AccessToken(new GitHub_AccessToken_RequestEntity() { code = authorizeResult.code }); //获取 user var userEntity = GitHub.User(new GitHub_User_RequestEntity() { access_token = tokenEntity.access_token }); openId = userEntity.id.ToString(); mo.OpenId3 = openId; mo.Nickname = userEntity.name; mo.UserSay = userEntity.bio; mo.UserUrl = userEntity.blog; mo.UserMail = userEntity.email; avatar = userEntity.avatar_url; avatarhd = userEntity.avatar_url; } break; case ValidateloginType.taobao: { //获取 access_token var tokenEntity = TaoBao.AccessToken(new TaoBao_AccessToken_RequestEntity() { code = authorizeResult.code }); openId = tokenEntity.open_uid; mo.OpenId4 = openId; mo.Nickname = "淘宝用户"; } break; case ValidateloginType.microsoft: { //获取 access_token var tokenEntity = MicroSoft.AccessToken(new MicroSoft_AccessToken_RequestEntity() { code = authorizeResult.code }); //获取 user var userEntity = MicroSoft.User(new MicroSoft_User_RequestEntity() { access_token = tokenEntity.access_token }); openId = userEntity.id.ToString(); mo.OpenId5 = openId; mo.Nickname = userEntity.last_name + userEntity.first_name; mo.UserMail = userEntity.emails["account"].ToStringOrEmpty(); } break; case ValidateloginType.dingtalk: { //获取 user var userEntity = DingTalk.User(new DingTalk_User_RequestEntity(), authorizeResult.code); openId = userEntity.openid; mo.OpenId6 = openId; mo.Nickname = userEntity.nick; } break; } mo.UserCreateTime = DateTime.Now; mo.UserName = openId; mo.UserPwd = Core.CalcTo.MD5(openId); if (!string.IsNullOrWhiteSpace(avatar)) { mo.UserPhoto = Core.UniqueTo.LongId().ToString() + ".jpg"; } if (string.IsNullOrWhiteSpace(openId)) { vm.Set(ARTag.unauthorized); vm.msg = "身份验证失败"; } else { //判断是绑定操作 bool isbind = User.Identity.IsAuthenticated && authorizeResult.state.StartsWith("bind"); if (isbind) { int uid = new Func.UserAuthAid(HttpContext).Get().UserId; using (var db = new ContextBase()) { //检测是否绑定其它账号 var queryIsBind = db.UserInfo.Where(x => x.UserId != uid); switch (vtype) { case ValidateloginType.qq: queryIsBind = queryIsBind.Where(x => x.OpenId1 == openId); break; case ValidateloginType.weibo: queryIsBind = queryIsBind.Where(x => x.OpenId2 == openId); break; case ValidateloginType.github: queryIsBind = queryIsBind.Where(x => x.OpenId3 == openId); break; case ValidateloginType.taobao: queryIsBind = queryIsBind.Where(x => x.OpenId4 == openId); break; case ValidateloginType.microsoft: queryIsBind = queryIsBind.Where(x => x.OpenId5 == openId); break; case ValidateloginType.dingtalk: queryIsBind = queryIsBind.Where(x => x.OpenId6 == openId); break; } if (queryIsBind.Count() > 0) { return(Content("已绑定其它账号,不能重复绑定")); } var userInfo = db.UserInfo.Find(uid); switch (vtype) { case ValidateloginType.qq: userInfo.OpenId1 = openId; break; case ValidateloginType.weibo: userInfo.OpenId2 = openId; break; case ValidateloginType.github: userInfo.OpenId3 = openId; break; case ValidateloginType.taobao: userInfo.OpenId4 = openId; break; case ValidateloginType.microsoft: userInfo.OpenId5 = openId; break; case ValidateloginType.dingtalk: userInfo.OpenId6 = openId; break; } db.UserInfo.Update(userInfo); db.SaveChanges(); } return(Redirect("/user/setting")); } else { using var db = new ContextBase(); Domain.UserInfo vmo = null; switch (vtype) { case ValidateloginType.qq: vmo = db.UserInfo.FirstOrDefault(x => x.OpenId1 == openId); break; case ValidateloginType.weibo: vmo = db.UserInfo.FirstOrDefault(x => x.OpenId2 == openId); break; case ValidateloginType.github: vmo = db.UserInfo.FirstOrDefault(x => x.OpenId3 == openId); break; case ValidateloginType.taobao: vmo = db.UserInfo.FirstOrDefault(x => x.OpenId4 == openId); break; case ValidateloginType.microsoft: vmo = db.UserInfo.FirstOrDefault(x => x.OpenId5 == openId); break; case ValidateloginType.dingtalk: vmo = db.UserInfo.FirstOrDefault(x => x.OpenId6 == openId); break; } //未注册 if (vmo == null) { var ruvm = RegisterUser(mo); if (ruvm.code == 200) { vm = ValidateLogin(vtype, mo); //拉取头像 if (vm.code == 200 && (!string.IsNullOrWhiteSpace(avatar) || !string.IsNullOrWhiteSpace(avatarhd))) { try { using var wc = new System.Net.WebClient(); var rootdir = GlobalTo.WebRootPath + "/" + (GlobalTo.GetValue("StaticResource:RootDir").TrimStart('/').TrimEnd('/') + "/"); var path = GlobalTo.GetValue("StaticResource:AvatarPath").TrimEnd('/').TrimStart('/') + '/'; var fullpath = rootdir + path; if (!System.IO.Directory.Exists(fullpath)) { System.IO.Directory.CreateDirectory(fullpath); } if (!string.IsNullOrWhiteSpace(avatar)) { wc.DownloadFile(avatar, fullpath + mo.UserPhoto); } if (!string.IsNullOrWhiteSpace(avatarhd)) { wc.DownloadFile(avatarhd, fullpath + mo.UserPhoto.Replace(".jpg", "_lg.jpg")); } } catch (Exception) { } } } else { vm.msg = ruvm.msg; } } else { vm = ValidateLogin(vtype, vmo); } } } } } catch (Exception ex) { vm.Set(ex); } //成功 if (vm.code == 200) { return(Redirect("/")); } else { string msg = "【登录失败】( " + vm.msg + " )".ToEncode(); return(Redirect("/home/error?msg=" + msg)); } }
/// <summary> /// 开发者接管 /// </summary> /// <param name="signature"></param> /// <param name="timestamp"></param> /// <param name="nonce"></param> /// <param name="echostr"></param> /// <param name="encrypt_type"></param> /// <param name="msg_signature"></param> public async void WeChat(string signature, string timestamp, string nonce, string echostr, string encrypt_type, string msg_signature) { string result = string.Empty; //微信后台验证地址(使用Get),微信后台的“接口配置信息”的Url if (Request.Method.ToLower() == "get") { var Token = GlobalTo.GetValue("ApiKey:WeChatMP:Token"); if (Netnr.WeChat.Helpers.Util.CheckSignature(signature, timestamp, nonce, Token)) { //返回随机字符串则表示验证通过 result = echostr; } else { result = "参数错误!"; } } //处理请求 else { WeChatMessage message = null; var safeMode = encrypt_type == "aes"; var Token = string.Empty; var EncodingAESKey = string.Empty; var AppID = string.Empty; if (safeMode) { Token = GlobalTo.GetValue("ApiKey:WeChatMP:Token"); EncodingAESKey = GlobalTo.GetValue("ApiKey:WeChatMP:EncodingAESKey"); AppID = GlobalTo.GetValue("ApiKey:WeChatMP:AppID"); } using (var ms = new MemoryStream()) { await Request.Body.CopyToAsync(ms); var myByteArray = ms.ToArray(); var decryptMsg = string.Empty; string postStr = System.Text.Encoding.UTF8.GetString(myByteArray); #region 解密 if (safeMode) { var wxBizMsgCrypt = new WeChat.Helpers.Crypto.WXBizMsgCrypt(Token, EncodingAESKey, AppID); var ret = wxBizMsgCrypt.DecryptMsg(msg_signature, timestamp, nonce, postStr, ref decryptMsg); //解密失败 if (ret != 0) { FilterConfigs.WriteLog(HttpContext, new Exception("微信解密失败")); } } else { decryptMsg = postStr; } #endregion message = WeChatMessage.Parse(decryptMsg); } var response = new WeChatExecutor().Execute(message); #region 加密 if (safeMode) { var wxBizMsgCrypt = new WeChat.Helpers.Crypto.WXBizMsgCrypt(Token, EncodingAESKey, AppID); var ret = wxBizMsgCrypt.EncryptMsg(response, timestamp, nonce, ref result); if (ret != 0)//加密失败 { FilterConfigs.WriteLog(HttpContext, new Exception("微信加密失败")); } } else { result = response; } #endregion } //输出 byte[] buffer = System.Text.Encoding.UTF8.GetBytes(result); await Response.Body.WriteAsync(buffer, 0, buffer.Length); await Response.Body.FlushAsync(); }
/// <summary> /// 处理微信消息 /// </summary> /// <param name="message"></param> /// <returns>已经打包成xml的用于回复用户的消息包</returns> public string Execute(WeChatMessage message) { var myDomain = GlobalTo.GetValue("Common:Domain"); string myPic = $"{myDomain}/favicon.svg"; var mb = message.Body; var openId = mb.GetText("FromUserName"); var myUserName = mb.GetText("ToUserName"); var news = new WeChatNews { title = GlobalTo.GetValue("Common:ChineseName") + "(Gist,Run,Doc,Draw)", description = GlobalTo.GetValue("Common:ChineseName") + ",技术分享博客、代码片段、在线运行代码、接口文档、绘制 等等", picurl = myPic, url = myDomain }; //默认首页 string result = ReplayPassiveMessage.RepayNews(openId, myUserName, news); switch (message.Type) { //文字消息 case WeChatMessageType.Text: { string Content = mb.GetText("Content"); string repmsg = string.Empty; if ("sj".Split(' ').ToList().Contains(Content)) { repmsg = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); } else if ("xh".Split(' ').ToList().Contains(Content)) { repmsg = "笑话\nhttps://ss.netnr.com/qiushibaike"; } else if ("note".Split(' ').ToList().Contains(Content)) { repmsg = $"记事\n{myDomain}/tool/note"; } else if ("gist".Split(' ').ToList().Contains(Content)) { repmsg = $"代码片段\n{myDomain}/gist/discover"; } else if ("doc".Split(' ').ToList().Contains(Content)) { repmsg = $"文档\n{myDomain}/doc/discover"; } else if ("cp lottery".Split(' ').ToList().Contains(Content)) { repmsg = "彩票\nhttps://ss.netnr.com/lottery"; } if (!string.IsNullOrWhiteSpace(repmsg)) { result = ReplayPassiveMessage.RepayText(openId, myUserName, repmsg); } } break; } return(result); }
// 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 => { //cookie存储需用户同意,欧盟新标准,暂且关闭,否则用户没同意无法写入 options.CheckConsentNeeded = context => false; options.MinimumSameSitePolicy = SameSiteMode.None; }); IMvcBuilder builder = services.AddControllersWithViews(options => { //注册全局错误过滤器 options.Filters.Add(new Filters.FilterConfigs.ErrorActionFilter()); //注册全局过滤器 options.Filters.Add(new Filters.FilterConfigs.GlobalActionAttribute()); }); #if DEBUG builder.AddRazorRuntimeCompilation(); #endif services.AddControllers().AddNewtonsoftJson(options => { //Action原样输出JSON options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver(); //日期格式化 options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss.fff"; }); //配置swagger services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "RF API", Description = string.Join(" ", new List <string> { "<b>Source</b>:<a target='_blank' href='https://github.com/netnr/np'>https://github.com/netnr/np</a>", "<b>Blog</b>:<a target='_blank' href='https://www.netnr.com'>https://www.netnr.com</a>" }) }); "ResponseFramework.Web,ResponseFramework.Application,Fast".Split(',').ToList().ForEach(x => { c.IncludeXmlComments(System.AppContext.BaseDirectory + "Netnr." + x + ".xml", true); }); }); //授权访问信息 services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options => { options.Cookie.Name = "netnrf_auth"; options.LoginPath = "/account/login"; }); //session services.AddSession(); //数据库连接池 services.AddDbContextPool <Data.ContextBase>(options => { Data.ContextBase.DCOB(options); }, 99); //定时任务 FluentScheduler.JobManager.Initialize(new Application.TaskService.Reg()); //配置上传文件大小限制(详细信息:FormOptions) services.Configure <FormOptions>(options => { options.MultipartBodyLengthLimit = GlobalTo.GetValue <int>("StaticResource:MaxSize") * 1024 * 1024; }); }
/// <summary> /// 首页 /// </summary> /// <param name="filename"></param> /// <param name="xml"></param> /// <param name="mof"></param> /// <returns></returns> public IActionResult Index(string filename, string xml, Blog.Domain.Draw mof) { var id = RouteData.Values["id"]?.ToString(); var sid = RouteData.Values["sid"]?.ToString(); var uinfo = new Blog.Application.UserAuthService(HttpContext).Get(); if (!string.IsNullOrWhiteSpace(filename)) { filename = filename.ToDecode(); } if (!string.IsNullOrWhiteSpace(xml)) { xml = xml.ToDecode(); } //新增 if (id == "open") { //编辑 if (!string.IsNullOrWhiteSpace(sid)) { var vm = new ActionResultVM(); using var db = new Blog.Data.ContextBase(); var mo = db.Draw.Find(sid); if (mo?.DrOpen == 1 || mo?.Uid == uinfo.UserId) { vm.Set(ARTag.success); vm.Data = mo; } else { vm.Set(ARTag.unauthorized); } return(Content(vm.ToJson())); } return(Ok()); } //新增、编辑表单 else if (id == "form") { object model = null; if (HttpContext.User.Identity.IsAuthenticated) { if (!string.IsNullOrWhiteSpace(sid)) { using var db = new Blog.Data.ContextBase(); var mo = db.Draw.Find(sid); if (mo.Uid == uinfo.UserId) { model = mo; } } } return(View("_PartialDrawForm", model)); } //保存标题等信息 else if (id == "saveform") { var vm = new ActionResultVM(); if (User.Identity.IsAuthenticated) { using var db = new Blog.Data.ContextBase(); int num = 0; if (string.IsNullOrWhiteSpace(mof.DrId)) { mof.DrId = mof.DrType[0] + Core.UniqueTo.LongId().ToString(); mof.DrCreateTime = DateTime.Now; mof.Uid = uinfo.UserId; mof.DrOrder = 100; db.Draw.Add(mof); num = db.SaveChanges(); } else { var newmo = db.Draw.Find(mof.DrId); if (newmo.Uid == uinfo.UserId) { newmo.DrRemark = mof.DrRemark; newmo.DrName = mof.DrName; newmo.DrOpen = mof.DrOpen; db.Draw.Update(newmo); num = db.SaveChanges(); } } vm.Set(num > 0); } else { vm.Set(ARTag.unauthorized); } if (vm.Code == 200) { return(Redirect("/draw/user/" + uinfo?.UserId)); } else { return(Content(vm.ToJson())); } } //保存内容 else if (id == "save") { var vm = new ActionResultVM(); if (User.Identity.IsAuthenticated) { using var db = new Blog.Data.ContextBase(); //新增 if (string.IsNullOrWhiteSpace(sid)) { var mo = new Blog.Domain.Draw { DrName = filename, DrContent = xml, DrId = mof.DrType[0] + Core.UniqueTo.LongId().ToString(), DrType = mof.DrType, DrCreateTime = DateTime.Now, DrOpen = 1, DrOrder = 100, DrStatus = 1, Uid = uinfo.UserId }; db.Draw.Add(mo); var num = db.SaveChanges(); vm.Set(num > 0); vm.Data = mo.DrId; } else { var mo = db.Draw.Find(sid); if (mo?.Uid == uinfo.UserId) { mo.DrName = filename; mo.DrContent = xml; db.Draw.Update(mo); var num = db.SaveChanges(); vm.Set(num > 0); } else { vm.Set(ARTag.unauthorized); } } } else { vm.Code = 1; vm.Msg = "未登录"; } return(Content(vm.ToJson())); } //删除 else if (id == "del") { var vm = new ActionResultVM(); if (User.Identity.IsAuthenticated) { using var db = new Blog.Data.ContextBase(); var mo = db.Draw.Find(sid); if (mo.Uid == uinfo.UserId) { db.Remove(mo); int num = db.SaveChanges(); vm.Set(num > 0); } else { vm.Set(ARTag.unauthorized); } } else { vm.Set(ARTag.unauthorized); } if (vm.Code == 200) { return(Redirect("/draw/discover")); } else { return(Content(vm.ToJson())); } } //插入图片 else if (id == "upload") { var errno = -1; var msg = "fail"; var url = ""; var vm = new Blog.Web.Controllers.APIController().API98(Request.Form.Files[0], GlobalTo.GetValue("StaticResource:DrawPath")); if (vm.Code == 200) { var jd = ((JObject)vm.Data); url = jd["server"].ToString() + jd["path"].ToString(); errno = 0; msg = "ok"; } return(Content(new { errno, msg, data = new { url } }.ToJson())); } ViewData["vid"] = id; var vname = string.Format("_Partial{0}View", id.StartsWith('m') ? "Mind" : "Draw"); return(View(vname)); }
public override void OnActionExecuting(ActionExecutingContext context) { var hc = context.HttpContext; //日志记录,设置“__nolog”参数可忽略日志记录,为压力测试等环境考虑(即一些不需要记录请求日志的需求) //如果需要记录更详细的日志,可提取请求的参数、表单信息写入日志 //可能信息量较大,需要考虑分开存储,推荐方案:使用sqlite-net-pcl包按月或按天拆分写入SQLite数据库文件 if (string.IsNullOrWhiteSpace(hc.Request.Query["__nolog"].ToString())) { string controller = context.RouteData.Values["controller"].ToString().ToLower(); string action = context.RouteData.Values["action"].ToString().ToLower(); string url = hc.Request.Path.ToString() + hc.Request.QueryString.Value; try { //客户端信息 var ct = new Core.ClientTo(hc); //用户信息 var userinfo = Func.Common.GetLoginUserInfo(hc); //日志保存 var mo = new Domain.SysLog() { LogId = Guid.NewGuid().ToString(), SuName = userinfo.UserName, SuNickname = userinfo.Nickname, LogAction = controller + "/" + action, LogUrl = url, LogIp = ct.IPv4, LogCreateTime = DateTime.Now, LogBrowserName = ct.BrowserName, LogSystemName = ct.SystemName, LogGroup = 1 }; try { //IP城市 var city = new ipdb.City(GlobalTo.GetValue("logs:ipdb").Replace("~", GlobalTo.ContentRootPath)); var ips = mo.LogIp.Split(','); var ipc = string.Empty; foreach (var ip in ips) { var listCity = city.find(ip.Trim().Replace("::1", "127.0.0.1"), "CN").Distinct(); ipc += string.Join(",", listCity).TrimEnd(',') + ";"; } mo.LogCity = ipc.TrimEnd(';'); } catch (Exception) { mo.LogCity = "fail"; } mo.LogContent = DicDescription[mo.LogAction.ToLower()]; #region 分批写入日志 //分批写入满足的条件:缓存的日志数量 int cacheLogCount = GlobalTo.GetValue <int>("logs:batchwritecount"); //分批写入满足的条件:缓存的时长,单位秒 int cacheLogTime = GlobalTo.GetValue <int>("logs:batchwritetime"); //日志记录 var cacheLogsKey = "Global_Logs"; //上次写入的时间 var cacheLogWriteKey = "Global_Logs_Write"; if (!(Core.CacheTo.Get(cacheLogsKey) is List <Domain.SysLog> cacheLogs)) { cacheLogs = new List <Domain.SysLog>(); } cacheLogs.Add(mo); var cacheLogWrite = Core.CacheTo.Get(cacheLogWriteKey) as DateTime?; if (!cacheLogWrite.HasValue) { cacheLogWrite = DateTime.Now; } if (cacheLogs?.Count > cacheLogCount || DateTime.Now.ToTimestamp() - cacheLogWrite.Value.ToTimestamp() > cacheLogTime) { using (var db = new Data.ContextBase()) { db.SysLog.AddRange(cacheLogs); db.SaveChanges(); } cacheLogs = null; cacheLogWrite = DateTime.Now; } Core.CacheTo.Set(cacheLogsKey, cacheLogs, 3600 * 24 * 30); Core.CacheTo.Set(cacheLogWriteKey, cacheLogWrite, 3600 * 24 * 30); #endregion } catch (Exception) { //throw new System.Exception("写入操作日志失败"); } } base.OnActionExecuting(context); }
public override void OnActionExecuting(ActionExecutingContext context) { var hc = context.HttpContext; //日志记录,设置“__nolog”参数可忽略日志记录,为压力测试等环境考虑(即一些不需要记录请求日志的需求) //如果需要记录更详细的日志,可提取请求的参数、表单信息写入日志 //可能信息量较大,需要考虑分开存储,推荐方案:使用sqlite-net-pcl包按月或按天拆分写入SQLite数据库文件 if (GlobalTo.GetValue <bool>("logs:enable") && string.IsNullOrWhiteSpace(hc.Request.Query["__nolog"].ToString())) { string controller = context.RouteData.Values["controller"].ToString().ToLower(); string action = context.RouteData.Values["action"].ToString().ToLower(); string url = hc.Request.Path.ToString() + hc.Request.QueryString.Value; try { //客户端信息 var ct = new Fast.ClientTo(hc); //用户信息 var userinfo = Func.Common.GetLoginUserInfo(hc); //日志保存 var mo = new Domain.SysLog() { LogId = Guid.NewGuid().ToString(), SuName = userinfo.UserName, SuNickname = userinfo.Nickname, LogAction = controller + "/" + action, LogUrl = url, LogIp = ct.IPv4.Split(',')[0].Trim(), LogCreateTime = DateTime.Now, LogBrowserName = ct.BrowserName, LogSystemName = ct.SystemName, LogGroup = 1 }; mo.LogContent = DicDescription[mo.LogAction.ToLower()]; #region 分批写入日志 //分批写入满足的条件:缓存的日志数量 int cacheLogCount = GlobalTo.GetValue <int>("logs:batchwritecount"); //分批写入满足的条件:缓存的时长,单位秒 int cacheLogTime = GlobalTo.GetValue <int>("logs:batchwritetime"); //日志记录 var cacheLogsKey = "Global_Logs"; //上次写入的时间 var cacheLogWriteKey = "Global_Logs_Write"; if (!(Core.CacheTo.Get(cacheLogsKey) is List <Domain.SysLog> cacheLogs)) { cacheLogs = new List <Domain.SysLog>(); } cacheLogs.Add(mo); var cacheLogWrite = Core.CacheTo.Get(cacheLogWriteKey) as DateTime?; if (!cacheLogWrite.HasValue) { cacheLogWrite = DateTime.Now; } if (cacheLogs?.Count > cacheLogCount || DateTime.Now.ToTimestamp() - cacheLogWrite.Value.ToTimestamp() > cacheLogTime) { //异步写入日志 System.Threading.ThreadPool.QueueUserWorkItem(_ => { //写入日志前查询IP所属区域 var dbpath = GlobalTo.GetValue("logs:dbpath").Replace("~", GlobalTo.ContentRootPath); using var ds = new IP2Region.DbSearcher(dbpath); foreach (var log in cacheLogs) { try { var ips = log.LogIp.Split(','); var ipi = new List <string>(); foreach (var ip in ips) { //内容格式:国家|区域|省份|市|运营商。无数据默认为0。 var listIpInfo = ds.MemorySearch(ip.Trim().Replace("::1", "127.0.0.1")).Region.Split('|').ToList(); listIpInfo.RemoveAt(1); listIpInfo = listIpInfo.Where(x => x != "0").Distinct().ToList(); ipi.Add(string.Join(",", listIpInfo)); } log.LogCity = string.Join(";", ipi); } catch (Exception) { log.LogCity = "fail"; } } using var db = new Data.ContextBase(Data.ContextBase.DCOB().Options); db.SysLog.AddRange(cacheLogs); db.SaveChanges(); //清空数据及更新时间 cacheLogs = null; cacheLogWrite = DateTime.Now; Core.CacheTo.Set(cacheLogsKey, cacheLogs, 3600 * 24 * 30); Core.CacheTo.Set(cacheLogWriteKey, cacheLogWrite, 3600 * 24 * 30); }); } else { Core.CacheTo.Set(cacheLogsKey, cacheLogs, 3600 * 24 * 30); Core.CacheTo.Set(cacheLogWriteKey, cacheLogWrite, 3600 * 24 * 30); } #endregion } catch (Exception) { //throw new System.Exception("写入操作日志失败"); } } base.OnActionExecuting(context); }