/// <summary> /// 更新用户头像 /// </summary> /// <param name="accountId"></param> /// <returns></returns> public async Task <Account> UpdateAccountHeadImgAsync(int accountId, string headImgUrl) { if (headImgUrl.IsNullOrEmpty()) { throw new Exception("headImgUrl为null,accountId:" + accountId); } var accountService = SenparcDI.GetService <AccountService>(); using (var wrap = accountService.InstanceAutoDetectChangeContextWrap()) { var account = accountService.GetObject(z => z.Id == accountId); if (account == null) { throw new Exception($"UserId不存在!ID:{accountId},HeadImgUrl:{headImgUrl}"); } var fileName = $@"/Upload/User/headimgurl.{DateTime.Now.Ticks + Guid.NewGuid().ToString("n").Substring(0, 8)}.jpg"; //下载图片 var t3 = DateTime.Now; await DownLoadPicAsync(headImgUrl, fileName); var t4 = DateTime.Now; LogUtility.Account.Debug($"更新用户头像(ID:{accountId},UserName:{account.UserName}),下载图片耗时:{(t4 - t3).TotalMilliseconds}ms"); //测试耗时:4226.5869ms account.PicUrl = fileName; //不使用七牛或其他云储存,就使用本地路径 accountService.SaveObject(account); return(account); } }
private static string GetPageLink(int linkPageIndex, int currentPageIndex, string text, string currentPageWordFormat, string onclick, string url, string barMark, bool inInframe) { //var pageData = "?page=";//string.Format("{0}page=", (Request.QueryString.Count == 0) ? "?" : "&") + "{0}";//页码参数 onclick = (onclick != null) ? "onclick=\"" + onclick + "\"" : ""; onclick = onclick.Replace("{pageindex}", linkPageIndex.ToString()); var httpContext = SenparcDI.GetService <IHttpContextAccessor>().HttpContext; url = (!string.IsNullOrEmpty(url)) ? url.UrlDecode().Replace(currentPageWordFormat, linkPageIndex.ToString()) : ""; var href = (onclick != null && onclick.IndexOf("return false") != -1) ? "href=\"#" + barMark + "\" " : "href=\"" + url + "\" "; var linkHTML = ""; string formatedText = currentPageWordFormat.IndexOf("{0}") >= 0 ? string.Format(currentPageWordFormat, text) : text;//判断是{0}形式还是自定义替换字符串。 if (linkPageIndex == currentPageIndex) { linkHTML = $"<span class=\"current\">{formatedText}</span>"; } else { linkHTML = "<a " + href + onclick + $" {(inInframe ? "data - iniframe =\"1\"" : null)}>{text}</a>"; } return(linkHTML); }
/// <summary> /// 操作列队 /// </summary> public static void OperateQueue() { lock (FlushCacheLock) { var mq = new OperationQueue(); var key = mq.GetCurrentKey(); //获取最新的Key while (!string.IsNullOrEmpty(key)) { try { var operationQueueService = SenparcDI.GetService <OperationQueueService>(); var mqItem = mq.GetItem(key); //获取任务项 //识别类型 switch (mqItem.OperationQueueType) { case OperationQueueType.更新用户头像: operationQueueService.UpdateAccountHeadImgAsync((int)mqItem.Data[0], mqItem.Data[1] as string).Wait(); break; default: LogUtility.OperationQueue.ErrorFormat("OperationQueueType未处理:{0}", mqItem.OperationQueueType.ToString()); break; } } catch (Exception ex) { LogUtility.OperationQueue.ErrorFormat($"OperationQueue列队操作失败,已经跳过:{ex.Message}", ex); } mq.Remove(key); //清除 key = mq.GetCurrentKey(); //获取最新的Key } } }
public string GetLastCount() { var senparcSmsSetting = SenparcDI.GetService <IOptions <SenparcSmsSetting> >(); var smsPlatform = SmsPlatformFactory.GetSmsPlateform(senparcSmsSetting.Value.SmsAccountCORPID, senparcSmsSetting.Value.SmsAccountName, senparcSmsSetting.Value.SmsAccountPassword, senparcSmsSetting.Value.SmsAccountSubNumber); return(smsPlatform.GetLastCount()); }
public void ChangePoint(int accountId, decimal accountPoints, string userName, decimal points, string description, bool notRecordIfPointIsZero = true, bool throwIfNotEnoughPoints = false) { if (notRecordIfPointIsZero && points == 0) { return;//积分为0则不更改 } if (throwIfNotEnoughPoints && points < 0 && accountPoints + points < 0) { //TODO 抛出异常待定 throw new Exception($"积分不足,还需{Convert.ToInt32(accountPoints + points)}积分!"); } var beforePoints = accountPoints; var afterPoints = beforePoints + points; var pointsLog = new PointsLog() { AccountId = accountId, AddTime = DateTime.Now, Description = description, Points = points, BeforePoints = beforePoints, AfterPoints = afterPoints }; this.SaveObject(pointsLog); //删除Account缓存 var fullAccountCache = SenparcDI.GetService <FullAccountCache>(); fullAccountCache.RemoveObject(userName); }
public override void OnActionExecuting(ActionExecutingContext context) { try { TempData["Messager"] = TempData["Messager"]; var fullSystemConfigCache = SenparcDI.GetService <FullSystemConfigCache>(); _fullSystemConfig = fullSystemConfigCache.Data; var fullAccountCache = SenparcDI.GetService <FullAccountCache>(); if (this.UserName != null) { FullAccount = fullAccountCache.GetObject(this.UserName); if (FullAccount != null) { //... } else { //用户不存在,发生严重异常 LogUtility.Account.Error($"发生严重错误,用户已登录,但缓存及数据库中不存在:{this.UserName}"); } } FullAccount = FullAccount ?? new FullAccount(); FullAccount.LastActiveTime = DateTime.Now; base.OnActionExecuting(context); } catch (Exception ex) { context.Result = RenderError(ex.Message, ex); } }
public void PayLogFinish(AccountPayLog accountPayLog) { if (accountPayLog.Status != (int)AccountPayLog_Status.未支付) { return; } try { var accountService = SenparcDI.GetService <AccountService>(); var account = accountService.GetObject(z => z.Id == accountPayLog.AccountId); using (var transcation = BeginTransaction()) { accountPayLog.Status = (int)AccountPayLog_Status.已支付; accountPayLog.CompleteTime = DateTime.Now; account.Points += accountPayLog.PayMoney; accountService.SaveObject(account); SaveObject(accountPayLog); transcation.Commit(); } } catch (Exception ex) { LogUtility.AccountPayLog.Error($"支付完成,发生错误:{ex.Message}", ex); throw new Exception($"支付回调失败【{ex.Message}】"); } }
public ClientRepositoryBase(ISqlClientFinanceData db) { //System.Web.HttpContext.Current.Response.Write("-"+this.GetType().Name + "<br />"); base.BaseDB = db ?? SenparcDI.GetService <ISqlClientFinanceData>();// ObjectFactory.GetInstance<ISqlClientFinanceData>(); _entitySetName = EntitySetKeys.Keys[typeof(T)]; }
static MemcachedStrategy() { // //初始化memcache服务器池 //SockIOPool pool = SockIOPool.GetInstance(); ////设置Memcache池连接点服务器端。 //pool.SetServers(serverlist); ////其他参数根据需要进行配置 //pool.InitConnections = 3; //pool.MinConnections = 3; //pool.MaxConnections = 5; //pool.SocketConnectTimeout = 1000; //pool.SocketTimeout = 3000; //pool.MaintenanceSleep = 30; //pool.Failover = true; //pool.Nagle = false; //pool.Initialize(); //cache = new MemcachedClient(); //cache.EnableCompression = false; try { //config.Authentication.Type = typeof(PlainTextAuthenticator); //config.Authentication.Parameters["userName"] = "******"; //config.Authentication.Parameters["password"] = "******"; //config.Authentication.Parameters["zone"] = "zone";//domain? ——Jeffrey 2015.10.20 DateTime dt1 = DateTime.Now; var config = GetMemcachedClientConfiguration(); ILoggerFactory loggerFactory = SenparcDI.GetService <ILoggerFactory>(); var cache = new MemcachedClient(loggerFactory, config); var testKey = Guid.NewGuid().ToString(); var testValue = Guid.NewGuid().ToString(); cache.Store(StoreMode.Set, testKey, testValue); var storeValue = cache.Get(testKey); if (storeValue as string != testValue) { throw new Exception("MemcachedStrategy失效,没有计入缓存!"); } cache.Remove(testKey); DateTime dt2 = DateTime.Now; LogUtility.Cache.Error($"MemcachedStrategy正常启用,启动及测试耗时:{(dt2 - dt1).TotalMilliseconds}ms"); } catch (Exception ex) { SiteConfig.CacheType = CacheType.Local;//强制切换到本地缓存状态 LogUtility.SystemLogger.ErrorFormat($"MemcachedStrategy静态构造函数异常:{ex.Message}", ex); throw new Exception("系统繁忙,请稍后再试!"); } }
public override void SaveObject(SystemConfig obj) { LogUtility.SystemLogger.Info("系统信息被编辑"); base.SaveObject(obj); //删除缓存 var systemConfigCache = SenparcDI.GetService <FullSystemConfigCache>(); systemConfigCache.RemoveCache(); }
public override void DeleteObject(Account obj) { obj.Flag = true; base.SaveObject(obj); LogUtility.WebLogger.Info($"User被删除:{obj.UserName}(ID:{obj.Id})"); //清除缓存 var fullUserCache = SenparcDI.GetService <FullAccountCache>(); fullUserCache.RemoveObject(obj.UserName); }
/// <summary> /// /// </summary> /// <param name="ip"></param> /// <param name="content"></param> /// <param name="phoneNumber"></param> /// <param name="addHotLine"></param> /// <param name="postfix"></param> /// <returns></returns> public SmsResult Send(string ip, string content, string phoneNumber, bool addHotLine = true, string postfix = " 客服热线:400-9939-858") { var senparcSmsSetting = SenparcDI.GetService <IOptions <SenparcSmsSetting> >(); ISmsPlatform smsPlatform = null; SmsResult smsResult = SmsResult.未知错误; content = $"【SCF】{content}{postfix}"; //加上签名和后缀 smsPlatform = SmsPlatformFactory.GetSmsPlateform(senparcSmsSetting.Value.SmsAccountCORPID, senparcSmsSetting.Value.SmsAccountName, senparcSmsSetting.Value.SmsAccountPassword, senparcSmsSetting.Value.SmsAccountSubNumber); smsResult = smsPlatform.Send(content, phoneNumber); return(smsResult); }
public RepositoryBase(ISqlBaseFinanceData db) : base(db) { //System.Web.HttpContext.Current.Response.Write("-"+this.GetType().Name + "<br />"); //DB = db ?? ObjectFactory.GetInstance<ISqlClientFinanceData>();//如果没有定义,取默认数据库 base.BaseDB = db ?? SenparcDI.GetService <ISqlBaseFinanceData>();// ObjectFactory.GetInstance<ISqlClientFinanceData>(); EntitySetKeysDictionary keys = EntitySetKeys.GetEntitySetKeys(base.BaseDB.BaseDataContext.GetType()); _entitySetName = keys[typeof(T)]; }
public BaseCache(string cacheKey, ISqlClientFinanceData db) { CacheKey = cacheKey; _db = db ?? SenparcDI.GetService <ISqlClientFinanceData>(); // if (TimeOut == 0) { TimeOut = 1440; } Cache = CacheStrategyFactory.GetObjectCacheStrategyInstance(); this.CacheSetKey = cacheKey;//设置缓存集合键,必须提供 }
public override FullSystemConfig Update() { var systemConfig = base._db.DataContext.SystemConfigs.FirstOrDefault(); FullSystemConfig fullSystemConfig = null; if (systemConfig != null) { fullSystemConfig = FullSystemConfig.CreateEntity <FullSystemConfig>(systemConfig); } else { string hostName = null; try { var httpContextAccessor = SenparcDI.GetService <IHttpContextAccessor>(); var httpContext = httpContextAccessor.HttpContext; var urlData = httpContext.Request; var scheme = urlData.Scheme; //协议 var host = urlData.Host.Host; //主机名(不带端口) var port = urlData.Host.Port ?? -1; //端口(因为从.NET Framework移植,因此不直接使用urlData.Host) string portSetting = null; //Url中的端口部分 string schemeUpper = scheme.ToUpper(); //协议(大写) string baseUrl = httpContext.Request.PathBase; //子站点应用路径 if (port == -1 || //这个条件只有在 .net core 中, Host.Port == null 的情况下才会发生 (schemeUpper == "HTTP" && port == 80) || (schemeUpper == "HTTPS" && port == 443)) { portSetting = "";//使用默认值 } else { portSetting = ":" + port;//添加端口 } hostName = $"{scheme}://{host}{portSetting}"; } catch { } throw new SCFExceptionBase($"SCF 系统未初始化,请先执行 {hostName}/Install 进行数据初始化"); } base.SetData(fullSystemConfig, base.TimeOut, null); return(base.Data); }
private static MemcachedClientConfiguration GetMemcachedClientConfiguration() { ILoggerFactory loggerFactory = SenparcDI.GetService <ILoggerFactory>(); IOptions <MemcachedClientOptions> optionsAccessor = SenparcDI.GetService <IOptions <MemcachedClientOptions> >(); //每次都要新建 var config = new MemcachedClientConfiguration(loggerFactory, optionsAccessor); foreach (var server in _serverlist) { config.Servers.Add(new DnsEndPoint(server.Key, server.Value)); } config.Protocol = MemcachedProtocol.Binary; return(config); }
public string ReplaceWeixinFace(string content) { var weixinFaceCahce = SenparcDI.GetService <WeixinFaceCache>(); foreach (var keyValuePair in weixinFaceCahce.Data) { var image = $"<img src=\"/Content/WeixinFace/{keyValuePair.Value}.png\" title=\"{keyValuePair.Value.ToString()}\" />"; //表情中有<>之类符号,需要考虑到进来的content已经HtmlEncode的情况 var encodedCode = keyValuePair.Key.HtmlEncode(); if (encodedCode != keyValuePair.Key) { content = content.Replace(keyValuePair.Key.HtmlEncode(), image); } content = content.Replace(keyValuePair.Key, image); } return(content); }
private string GetRegQrCode(Guid guid) { var sceneId = int.Parse(DateTime.Now.ToString("MMddHHmmss")); var senparcWeixinConfig = SenparcDI.GetService <IOptions <SenparcWeixinSetting> >().Value; var qrCodeRegCache = SenparcDI.GetService <QrCodeRegCache>(); while (qrCodeRegCache.MessageCollection.ContainsKey(sceneId.ToString())) { sceneId++; } CreateQrCodeResult qrCodeResult = QrCodeApi.Create(senparcWeixinConfig.WeixinAppId, 600, sceneId, QrCode_ActionName.QR_SCENE, "reg_code"); var qrCodeRegData = new QrCodeRegData(sceneId, qrCodeResult.expire_seconds, qrCodeResult.ticket, guid, QrCodeRegDataType.Reg); qrCodeRegCache.Insert(qrCodeRegData, qrCodeRegData.Key); return(qrCodeResult.url); }
public virtual void Logout() { try { var fullAccountCache = SenparcDI.GetService <FullAccountCache>(); fullAccountCache.ForceLogout(_httpContextAccessor.Value.HttpContext.User.Identity.Name); _httpContextAccessor.Value.HttpContext.SignOutAsync( UserAuthorizeAttribute.AuthenticationScheme); //FormsAuthentication.SignOut(); //退出网站登录 //继续删除其他登陆信息 } catch (Exception ex) { Log.LogUtility.Account.Error("退出登录失败。", ex); } }
public void GetServiceTest() { BaseTest.RegisterServiceCollection(); BaseTest.RegisterServiceStart(true); var memcache = SenparcDI.GetService <IMemoryCache>(); Assert.IsNotNull(memcache); Console.WriteLine($"memcache HashCode:{memcache.GetHashCode()}"); var key = Guid.NewGuid().ToString(); var dt = SystemTime.Now; memcache.Set(key, dt);//直接使用缓存 var memcache2 = SenparcDI.GetService <IMemoryCache>(); Console.WriteLine($"memcache 2 HashCode:{memcache2.GetHashCode()}"); Assert.AreEqual(memcache.GetHashCode(), memcache2.GetHashCode());//同一个全局对象 var obj0 = memcache2.Get(key); Assert.IsNotNull(obj0); Assert.AreEqual(dt, obj0); //使用本地缓存测试 CacheStrategyFactory.RegisterObjectCacheStrategy(() => LocalObjectCacheStrategy.Instance); var cache = CacheStrategyFactory.GetObjectCacheStrategyInstance(); var obj1 = cache.Get(key, true);//使用缓存策略获取 Assert.IsNotNull(obj1); Assert.AreEqual(dt, obj1); var obj2 = cache.Get <DateTimeOffset>(key, true);//获取明确类型对象 Assert.IsNotNull(obj2); Assert.AreEqual(dt, obj2); Assert.AreEqual(obj0.GetHashCode(), obj2.GetHashCode()); }
public override IResponseMessageBase OnEvent_ScanRequest(RequestMessageEvent_Scan requestMessage) { try { if (int.TryParse(requestMessage.EventKey, out int sceneId)) { //临时二维码 var qrCodeRegCache = SenparcDI.GetService <QrCodeRegCache>(); var qrCodeRegData = qrCodeRegCache.Get(sceneId.ToString()); if (qrCodeRegData?.Data != null && qrCodeRegData.Data.Ticket == requestMessage.Ticket) { var responseRegMessage = CreateResponseMessage <ResponseMessageText>(); if (qrCodeRegData.Data.QrCodeRegDataType == QrCodeRegDataType.Reg) { var userService = SenparcDI.GetService <AccountService>(); //判断是否已经绑定[CodeChecked] if (userService.GetCount(z => z.WeixinOpenId == requestMessage.FromUserName) <= 0) { var code = new Random().Next(100000, 999999).ToString(); qrCodeRegData.Data.Code = code; qrCodeRegData.Data.OpenId = requestMessage.FromUserName; qrCodeRegCache.Remove(sceneId.ToString()); qrCodeRegCache.Insert(qrCodeRegData.Data, sceneId.ToString()); responseRegMessage.Content = "验证码:" + code; } else { responseRegMessage.Content = "您的微信已绑定SCF账户,不能重复绑定!"; } return(responseRegMessage); } } } } catch (Exception ex) { LogUtility.Weixin.Error(ex.Message, ex); } return(base.OnEvent_ScanRequest(requestMessage)); }
public override void SaveObject(Account obj) { var isInsert = base.IsInsert(obj); if (isInsert) { obj.Flag = false; } base.SaveObject(obj); LogUtility.WebLogger.InfoFormat("User{2}:{0}(ID:{1})", obj.UserName, obj.Id, isInsert ? "新增" : "编辑"); //清除缓存 var fullUserCache = SenparcDI.GetService <FullAccountCache>(); //示范同步缓存锁 using (fullUserCache.Cache.BeginCacheLock(FullAccountCache.CACHE_KEY, obj.Id.ToString())) { fullUserCache.RemoveObject(obj.UserName); } }
public SmsResult SendPhoneCheck(string ip, string phoneNumber, string token, bool checkToken, string format = "") { if (checkToken) { var savedToken = _httpContextAccessor.HttpContext.Session.GetString(TokenSessionKey); if (savedToken.IsNullOrEmpty() || savedToken.Length != 32 || savedToken != token) { return(SmsResult.请在60秒后重试); } } //生成并储存验证码 var phoneCheckCodeCache = SenparcDI.GetService <PhoneCheckCodeCache>(); string code = phoneCheckCodeCache.Insert(new PhoneCheckCodeData(phoneNumber), null); //发送短信 var smsResult = Send(ip, string.Format(format, code), phoneNumber); return(smsResult); }
protected override bool AuthorizeCore(HttpContext httpContext) { //return base.AuthorizeCore(httpContext); if (httpContext == null) { throw new ArgumentNullException("httpContext"); } IPrincipal user = httpContext.User; if (!base.IsLogined(httpContext)) { return(false);//未登录 } var result = base.AuthorizeCore(httpContext);// base.AuthorizeCore(httpContext); if (result) { #if !DEBUG var adminSession = httpContext.Session.GetString("AdminLogin") as string; if (adminSession.IsNullOrEmpty()) { try { AccountService accountService = SenparcDI.GetService <AccountService>(); accountService.Logout();//强制退出登陆 } catch { } result = false; } #endif } return(result); }
/// <summary> /// 下载微信临时素材Image /// </summary> /// <param name="serverId"></param> /// <param name="fileName"></param> /// <param name="getNewToken"></param> /// <returns></returns> public bool DownloadTemplate(string serverId, string fileName, bool getNewToken = false) { using (MemoryStream ms = new MemoryStream()) { var senparcWeixinSetting = SenparcDI.GetService <IOptions <SenparcWeixinSetting> >().Value; MediaApi.Get(senparcWeixinSetting.WeixinAppId, serverId, ms); //保存到文件 ms.Position = 0; byte[] buffer = new byte[1024]; int bytesRead = 0; //判断是否上传成功 byte[] topBuffer = new byte[1]; ms.Read(topBuffer, 0, 1); if (topBuffer[0] == '{') { //写入日志 ms.Position = 0; byte[] logBuffer = new byte[1024]; ms.Read(logBuffer, 0, logBuffer.Length); string str = System.Text.Encoding.Default.GetString(logBuffer); Senparc.Ncf.Log.LogUtility.Weixin.InfoFormat("下载失败:{0}。serverId:{1}", str, serverId); return(false); } ms.Position = 0; //创建目录 using (FileStream fs = new FileStream(fileName, FileMode.Create)) { while ((bytesRead = ms.Read(buffer, 0, buffer.Length)) != 0) { fs.Write(buffer, 0, bytesRead); } fs.Flush(); } Senparc.Ncf.Log.LogUtility.Weixin.InfoFormat("下载成功:Path[{0}]", fileName); } return(true); }
public ServiceBase(IRepositoryBase <T> repo, IMapper mapper = null) : base(repo) { RepositoryBase = repo; Mapper = mapper == null?SenparcDI.GetService <IMapper>() : mapper;//确保 Mapper 中有值 }
public void ThreadAndGlobalServiceTest() { BaseTest.RegisterServiceCollection(); BaseTest.RegisterServiceStart(true); SenparcDI.GlobalServiceCollection.AddScoped <SenparcSetting>(); SenparcDI.GlobalIServiceProvider = null; //测试跨线程唯一 var s = SenparcDI.GetService <SenparcSetting>(true); Console.WriteLine($"s:{s.GetHashCode()}"); var threadsCount = 10; Console.WriteLine("======= 开始全局唯一测试 ======="); var finishedThread = 0; for (int i = 0; i < threadsCount; i++) { var index = i; var thread = new Thread(() => { var s1 = SenparcDI.GetService <SenparcSetting>(true); var s2 = SenparcDI.GetService <SenparcSetting>(true); Console.WriteLine("ServiceProcider:" + SenparcDI.GlobalIServiceProvider?.GetHashCode()); Console.WriteLine($"{index}:{s1.GetHashCode()}"); Console.WriteLine($"{index}:{s2.GetHashCode()}"); Assert.AreEqual(s1.GetHashCode(), s2.GetHashCode()); finishedThread++; }); thread.Start(); } while (finishedThread != threadsCount) { } //所有HashCode相同 //测试通线程唯一 Console.WriteLine("======= 开始线程内唯一测试 ======="); finishedThread = 0; for (int i = 0; i < threadsCount; i++) { var thread = new Thread(() => { var index = i; Console.WriteLine($"-------{index}----------"); var threadScope = Thread.GetData(Thread.GetNamedDataSlot(CO2NET.SenparcDI.SENPARC_DI_THREAD_SERVICE_Scope)) as IServiceScope; Console.WriteLine("ServiceScope:" + threadScope?.GetHashCode()); Console.WriteLine("ServiceProcider:" + threadScope?.ServiceProvider.GetHashCode()); var s1 = SenparcDI.GetService <SenparcSetting>(false); var s2 = SenparcDI.GetService <SenparcSetting>(false); Console.WriteLine($"{index}:{s1.GetHashCode()}"); Console.WriteLine($"{index}:{s2.GetHashCode()}"); Assert.AreEqual(s1.GetHashCode(), s2.GetHashCode()); threadScope = Thread.GetData(Thread.GetNamedDataSlot(CO2NET.SenparcDI.SENPARC_DI_THREAD_SERVICE_Scope)) as IServiceScope; Console.WriteLine("ServiceScope:" + threadScope.GetHashCode()); Console.WriteLine("ServiceProcider:" + threadScope.ServiceProvider.GetHashCode()); Console.WriteLine("-----------------"); finishedThread++; }); thread.Start(); } while (finishedThread != threadsCount) { } //单线程内HashCode相同 }
public ActionResult UploadKindEditor(IFormFile imgFile, string dir) { try { //定义允许上传的文件扩展名 Hashtable extTable = new Hashtable(); extTable.Add("image", "gif,jpg,jpeg,png,bmp"); extTable.Add("flash", "swf,flv"); extTable.Add("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb"); extTable.Add("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2"); //获取文件名 string sFilename = System.IO.Path.GetFileName(imgFile.FileName).ToLower(); //获取upImage文件的扩展名 string extendName = System.IO.Path.GetExtension(sFilename); //最大文件大小 int maxSize = 1024 * 1024 * 1024; if (imgFile == null) { SetMessager(Core.Enums.MessageType.danger, "请选择文件。"); //showError("请选择文件。"); } if (imgFile == null || imgFile.Length > maxSize) { SetMessager(Core.Enums.MessageType.danger, "上传文件大小超过限制。"); //showError("上传文件大小超过限制。"); } String dirName = dir; if (String.IsNullOrEmpty(dirName)) { dirName = "image"; } if (String.IsNullOrEmpty(extendName) || Array.IndexOf(((String)extTable[dirName]).Split(','), extendName.Substring(1).ToLower()) == -1) { SetMessager(Core.Enums.MessageType.danger, "上传文件扩展名是不允许的扩展名。\n只允许" + ((String)extTable[dirName]) + "格式。"); // showError(); } long fileLeng = imgFile.Length; byte[] photoValue = new byte[fileLeng]; try { using (var ms = new MemoryStream()) { imgFile.CopyTo(ms); var fileBytes = ms.ToArray(); photoValue = fileBytes; } } catch (Exception ex) { } finally { } string strDateTime = DateTime.Now.ToString("yyMMddhhmmssfff"); //取得时间字符串 string strRan = Convert.ToString(new Random().Next(100, 999)); //生成三位随机数 string saveName = strDateTime + strRan + extendName; var senparcQiniuSetting = SenparcDI.GetService <IOptions <SenparcQiniuSetting> >(); //Common.AliyunOSS.CreateBucket(bucketName); if (QiniuClient.UploadFileData(saveName, photoValue, "richedit/")) { String fileUrl = "http://" + senparcQiniuSetting.Value.QiniuOSSAddress + "/richedit/" + saveName; Hashtable hash = new Hashtable(); hash["error"] = 0; hash["url"] = fileUrl; Response.Headers.Add("Content-Type", "text/html; charset=UTF-8"); using (StreamWriter sw = new StreamWriter(Response.Body)) { sw.Write(JsonConvert.SerializeObject(hash)); } return(new EmptyResult()); } else { } } catch (Exception ex) { SetMessager(Core.Enums.MessageType.danger, "上传文件到OSS出错!"); } return(new EmptyResult()); }
public IActionResult Imgupload(List <IFormFile> files) { long size = files.Sum(f => f.Length); var fileFolder = Path.Combine(_env.WebRootPath, "scfrichedit"); if (!Directory.Exists(fileFolder)) { Directory.CreateDirectory(fileFolder); } foreach (var formFile in files) { if (formFile.Length > 0) { Hashtable extTable = new Hashtable(); extTable.Add("image", "gif,jpg,jpeg,png,bmp"); //获取文件名 string sFilename = System.IO.Path.GetFileName(formFile.FileName).ToLower(); //获取upImage文件的扩展名 string extendName = System.IO.Path.GetExtension(sFilename); //最大文件大小 int maxSize = 1024 * 1024 * 1024; if (formFile == null) { SetMessager(Core.Enums.MessageType.danger, "请选择文件。"); //showError("请选择文件。"); } if (formFile == null || formFile.Length > maxSize) { SetMessager(Core.Enums.MessageType.danger, "上传文件大小超过限制。"); //showError("上传文件大小超过限制。"); } String dirName = ""; if (String.IsNullOrEmpty(dirName)) { dirName = "image"; } if (String.IsNullOrEmpty(extendName) || Array.IndexOf(((String)extTable[dirName]).Split(','), extendName.Substring(1).ToLower()) == -1) { return(Json(new UpLoadResult() { append = true, error = "上传失败:" + "上传文件扩展名是不允许的扩展名。\n只允许" + ((String)extTable[dirName]) + "格式。", initialPreview = new List <string> { "http://arbookresouce.73data.cn//arappbg.jpg" }, initialPreviewConfig = new List <InitialPreviewConfig> { new InitialPreviewConfig { caption = "", key = "0", size = 10240, url = Request.Scheme + "://" + Request.Host + "/Upload/ImguploadDel?key=124", width = "120px" } }, })); } long fileLeng = formFile.Length; byte[] photoValue = new byte[fileLeng]; try { using (var ms = new MemoryStream()) { formFile.CopyTo(ms); var fileBytes = ms.ToArray(); photoValue = fileBytes; } } catch (Exception ex) { } finally { } string strDateTime = DateTime.Now.ToString("yyMMddhhmmssfff"); //取得时间字符串 string strRan = Convert.ToString(new Random().Next(100, 999)); //生成三位随机数 string saveName = strDateTime + strRan + extendName; //var fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + // Path.GetExtension(formFile.FileName); var filePath = Path.Combine(fileFolder, saveName); try { FileExtension.Upload(formFile, filePath); } catch (Exception ex) { } var senparcQiniuSetting = SenparcDI.GetService <IOptions <SenparcQiniuSetting> >(); if (QiniuClient.UploadFileData(saveName, photoValue, "scfrichedit/")) { String fileUrl = "http://" + senparcQiniuSetting.Value.QiniuOSSAddress + "/scfrichedit/" + saveName; Hashtable hash = new Hashtable(); hash["error"] = 0; hash["url"] = fileUrl; return(Json(new UpLoadResult() { append = true, error = "", code = 0, curl = fileUrl, initialPreview = new List <string> { fileUrl }, initialPreviewConfig = new List <InitialPreviewConfig> { new InitialPreviewConfig { caption = "", key = "0", size = formFile.Length, url = Request.Scheme + "://" + Request.Host + "/Upload/ImguploadDel?key=124", width = "120px" } }, })); } else { } //using (var stream = new FileStream(filePath, FileMode.Create)) //{ // formFile.CopyTo(stream); //} } } return(Json(new UpLoadResult() { append = true, error = "上传失败", initialPreview = new List <string> { "http://arbookresouce.73data.cn//arappbg.jpg" }, initialPreviewConfig = new List <InitialPreviewConfig> { new InitialPreviewConfig { caption = "", key = "0", size = 10240, url = Request.Scheme + "://" + Request.Host + "/Upload/ImguploadDel?key=124", width = "120px" } }, })); }
public ActionResult Register(Home_RegisterVD vd_form) { //判断是否已经绑定微信 var codeRegCache = SenparcDI.GetService <QrCodeRegCache>(); var messageItem = codeRegCache.MessageQueue.FirstOrDefault(z => z.Data.RegGuid == vd_form.RegGuid); if (messageItem != null) { //允许注册 var qrCodeRegData = messageItem.Data; var user = _accountService.GetObject(z => z.WeixinOpenId == qrCodeRegData.OpenId); if (user != null) { return(RedirectToAction("Login", "Home")); } } else { //未发送验证码 return(RedirectToAction("Register", "Home")); } var userNameForbiddenWords = new[] { "@", "~", "`", "\"", "/", "<", ">", "'", "*", " ", " " }; this.Validator(vd_form.UserName, "用户名", "UserName", false) .IsFalse(z => userNameForbiddenWords.Any(z.Contains), "{0}不能包含空格及特殊字符!", true) .MinLength(4) .IsFalse(z => Regex.IsMatch(z, @"^\d+$"), "不能全是数字", true) .IsFalse(z => _accountService.CheckUserNameExisted(0, z), "{0}已存在!", true); this.Validator(vd_form.Password, "密码", "Password") .IsNotNull(vd_form.Password, "请填写密码!", true) .MinLength(6) .IsEqual(vd_form.RePassword, "两次密码不一致", true); this.Validator(vd_form.Email, "Email", "Email", false) .IsEmail(true) .IsFalse(z => _accountService.CheckEmailExisted(0, z), "{0}已存在!", true); this.Validator(vd_form.Phone, "手机号", "Phone", false).IsMobile(true) .IsFalse(z => _accountService.CheckPhoneExisted(0, z), "{0}已存在!", true); var phoneCheckVal = this.Validator(vd_form.PhoneCheck, "验证码", "PhoneCheck", false); var qrCodeCheckVal = this.Validator(vd_form.QrCodeCheck, "微信验证码", "QrCodeCheck", false); if (ModelState.IsValid) { if (!SiteConfig.IsDebug) { //短信验证 var phoneCheckCodeCache = SenparcDI.GetService <PhoneCheckCodeCache>(); var data = phoneCheckCodeCache.Get(vd_form.PhoneCheck); phoneCheckVal.IsTrue(z => data != null && data.Data.Phone == vd_form.Phone, "{0}错误!", true); qrCodeCheckVal.IsTrue(z => messageItem.Data != null && messageItem.Data.Code == vd_form.QrCodeCheck, "{0}错误!", true); } } if (!ModelState.IsValid) { var smsRecord = SenparcDI.GetService <SmsRecordService>(); var smsToken = smsRecord.GetSendSmsToken();//获取已经保存的令牌 vd_form.SmsToken = smsToken; return(View(vd_form)); } try { _accountService.CreateAccount(vd_form.UserName.Trim(), vd_form.Email.Trim(), vd_form.Phone.Trim(), vd_form.Password.Trim(), messageItem.Data.OpenId, "", ""); codeRegCache.Remove(messageItem.Data.Key);//删除缓存记录 SetMessager(MessageType.success, "注册成功"); return(RedirectToAction("Login")); } catch (Exception) { SetMessager(MessageType.danger, "注册失败,请稍后重试"); var smsRecord = SenparcDI.GetService <SmsRecordService>(); var smsToken = smsRecord.GetSendSmsToken();//获取已经保存的令牌 vd_form.SmsToken = smsToken; return(View(vd_form)); } }