/// <summary> /// 使用Get方法获取字符串结果(没有加入Cookie) /// </summary> /// <param name="url"></param> /// <returns></returns> public static string HttpGet(string url, Encoding encoding = null) { #if NET35 || NET40 || NET45 WebClient wc = new WebClient(); wc.Proxy = _webproxy; wc.Encoding = encoding ?? Encoding.UTF8; return(wc.DownloadString(url)); #else var handler = HttpClientHelper.GetHttpClientHandler(null, SenparcHttpClientWebProxy, DecompressionMethods.GZip); HttpClient httpClient = SenparcDI.GetRequiredService <SenparcHttpClient>().Client; return(httpClient.GetStringAsync(url).Result); #endif }
/// <summary> /// .NET Core 版本的HttpWebRequest参数设置 /// </summary> /// <returns></returns> private static HttpClient HttpGet_Common_NetCore(string url, CookieContainer cookieContainer = null, Encoding encoding = null, X509Certificate2 cer = null, string refererUrl = null, bool useAjax = false, int timeOut = Config.TIME_OUT) { var handler = HttpClientHelper.GetHttpClientHandler(cookieContainer, RequestUtility.SenparcHttpClientWebProxy, DecompressionMethods.GZip); if (cer != null) { handler.ClientCertificates.Add(cer); } HttpClient httpClient = SenparcDI.GetRequiredService <SenparcHttpClient>().Client; HttpClientHeader(httpClient, refererUrl, useAjax, null, timeOut); return(httpClient); }
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); }
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 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); }
/// <summary> /// 使用Get方法获取字符串结果(没有加入Cookie) /// </summary> /// <param name="url"></param> /// <returns></returns> public static async Task <string> HttpGetAsync(string url, Encoding encoding = null) { #if NET35 || NET40 || NET45 WebClient wc = new WebClient(); wc.Proxy = _webproxy; wc.Encoding = encoding ?? Encoding.UTF8; return(await wc.DownloadStringTaskAsync(url).ConfigureAwait(false)); #else var handler = new HttpClientHandler { UseProxy = SenparcHttpClientWebProxy != null, Proxy = SenparcHttpClientWebProxy, }; HttpClient httpClient = SenparcDI.GetRequiredService <SenparcHttpClient>().Client; return(await httpClient.GetStringAsync(url).ConfigureAwait(false)); #endif }
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); } }
/// <summary> /// 【异步方法】使用Post方法上传数据并下载文件或结果 /// </summary> /// <param name="url"></param> /// <param name="data"></param> /// <param name="stream"></param> public static async Task DownloadAsync(string url, string data, Stream stream) { #if NET35 || NET40 || NET45 WebClient wc = new WebClient(); var fileBytes = await wc.UploadDataTaskAsync(url, "POST", Encoding.UTF8.GetBytes(string.IsNullOrEmpty(data) ? "" : data)).ConfigureAwait(false); await stream.WriteAsync(fileBytes, 0, fileBytes.Length).ConfigureAwait(false);//也可以分段写入 #else HttpClient httpClient = SenparcDI.GetRequiredService <SenparcHttpClient>().Client; HttpContent hc = new StringContent(data); var ht = await httpClient.PostAsync(url, hc).ConfigureAwait(false); var fileBytes = await ht.Content.ReadAsByteArrayAsync().ConfigureAwait(false); await stream.WriteAsync(fileBytes, 0, fileBytes.Length).ConfigureAwait(false);//也可以分段写入 #endif }
public override IResponseMessageBase OnEvent_ScanRequest(RequestMessageEvent_Scan requestMessage) { try { if (int.TryParse(requestMessage.EventKey, out int sceneId)) { var serviceProvider = SenparcDI.GetServiceProvider(); //临时二维码 var qrCodeRegCache = serviceProvider.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 = serviceProvider.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 = "您的微信已绑定NCF账户,不能重复绑定!"; } return(responseRegMessage); } } } } catch (Exception ex) { LogUtility.Weixin.Error(ex.Message, ex); } return(base.OnEvent_ScanRequest(requestMessage)); }
/// <summary> /// 【异步方法】从Url下载,并保存到指定目录 /// </summary> /// <param name="url">需要下载文件的Url</param> /// <param name="filePathName">保存文件的路径,如果下载文件包含文件名,按照文件名储存,否则将分配Ticks随机文件名</param> /// <param name="timeOut">超时时间</param> /// <returns></returns> public static async Task <string> DownloadAsync(string url, string filePathName, int timeOut = Config.TIME_OUT) { var dir = Path.GetDirectoryName(filePathName) ?? "/"; Directory.CreateDirectory(dir); #if NET45 System.Net.Http.HttpClient httpClient = new HttpClient(); #else System.Net.Http.HttpClient httpClient = SenparcDI.GetRequiredService <SenparcHttpClient>().Client; #endif httpClient.Timeout = TimeSpan.FromMilliseconds(timeOut); using (var responseMessage = await httpClient.GetAsync(url).ConfigureAwait(false)) { if (responseMessage.StatusCode == HttpStatusCode.OK) { string responseFileName = null; //ContentDisposition可能会为Null if (responseMessage.Content.Headers.ContentDisposition != null && responseMessage.Content.Headers.ContentDisposition.FileName != null && responseMessage.Content.Headers.ContentDisposition.FileName != "\"\"") { responseFileName = Path.Combine(dir, responseMessage.Content.Headers.ContentDisposition.FileName.Trim('"')); } var fullName = responseFileName ?? Path.Combine(dir, GetRandomFileName()); using (var fs = File.Open(fullName, FileMode.Create)) { using (var responseStream = await responseMessage.Content.ReadAsStreamAsync().ConfigureAwait(false)) { await responseStream.CopyToAsync(fs).ConfigureAwait(false); await fs.FlushAsync().ConfigureAwait(false); } } return(fullName); } else { return(null); } } }
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 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); }
public static IServiceCollection AddSenparcEntitiesDI(this IServiceCollection services) { //var connectionString = Senparc.Scf.Core.Config.SenparcDatabaseConfigs.ClientConnectionString; //services.AddDbContext<SenparcEntities>(options => options.UseSqlServer(connectionString, b => b.MigrationsAssembly("Senparc.Web"))); services.AddScoped(s => new SenparcEntities(new DbContextOptionsBuilder <SenparcEntities>() .UseSqlServer(Scf.Core.Config.SenparcDatabaseConfigs.ClientConnectionString) .Options)); //#if DEBUG // var connectionString = Senparc.Scf.Core.Config.SenparcDatabaseConfigs.ClientConnectionString; // services.AddDbContext<SenparcEntities>(options => options.UseSqlServer(connectionString, b => b.MigrationsAssembly("Senparc.Web"))); //#else // services.AddScoped(s => new SenparcEntities(new DbContextOptionsBuilder<SenparcEntities>() // .UseSqlServer(Config.SenparcDatabaseConfigs.ClientConnectionString) // .Options)); //#endif SenparcDI.ResetGlobalIServiceProvider();//清空缓存,下次使用DI会自动重新Build return(services); }
/// <summary> /// 注册 IServiceCollection,并返回 RegisterService,开始注册流程(必须) /// </summary> /// <param name="serviceCollection">IServiceCollection</param> /// <param name="certName">证书名称,必须全局唯一,并且确保在全局 HttpClientFactory 内唯一</param> /// <param name="cert">证书对象,也可以是 X509Certificate2</param> /// <param name="checkValidationResult">设置</param> /// <returns></returns> public static IServiceCollection AddSenparcHttpClientWithCertificate(this IServiceCollection serviceCollection, string certName, X509Certificate cert, bool checkValidationResult = false) { serviceCollection.AddHttpClient <SenparcHttpClient>(certName) .ConfigurePrimaryHttpMessageHandler(() => { var httpClientHandler = HttpClientHelper.GetHttpClientHandler(null, RequestUtility.SenparcHttpClientWebProxy, System.Net.DecompressionMethods.GZip); httpClientHandler.ClientCertificates.Add(cert); if (checkValidationResult) { httpClientHandler.ServerCertificateCustomValidationCallback = new Func <HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool>(RequestUtility.CheckValidationResult); } return(httpClientHandler); }); SenparcDI.ResetGlobalIServiceProvider();//重置 GlobalIServiceProvider return(serviceCollection); }
private static MemcachedClientConfiguration GetMemcachedClientConfiguration(/*ILoggerFactory loggerFactory, IOptions<MemcachedClientOptions> optionsAccessor*/) #endif { //每次都要新建 #if NET45 var config = new MemcachedClientConfiguration(); foreach (var server in _serverlist) { config.Servers.Add(new IPEndPoint(IPAddress.Parse(server.Key), server.Value)); } config.Protocol = MemcachedProtocol.Binary; #else var provider = SenparcDI.GetIServiceProvider(); ILoggerFactory loggerFactory = provider.GetService <ILoggerFactory>(); IOptions <MemcachedClientOptions> optionsAccessor = provider.GetService <IOptions <MemcachedClientOptions> >(); var config = new MemcachedClientConfiguration(loggerFactory, optionsAccessor); #endif return(config); }
/// <summary> /// 从Url下载 /// </summary> /// <param name="url"></param> /// <param name="stream"></param> public static void Download(string url, Stream stream) { #if NET35 || NET40 || NET45 //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); WebClient wc = new WebClient(); var data = wc.DownloadData(url); stream.Write(data, 0, data.Length); //foreach (var b in data) //{ // stream.WriteByte(b); //} #else HttpClient httpClient = SenparcDI.GetRequiredService <SenparcHttpClient>().Client; var t = httpClient.GetByteArrayAsync(url); t.Wait(); var data = t.Result; stream.Write(data, 0, data.Length); #endif }
/// <summary> /// 【异步方法】异步从Url下载 /// </summary> /// <param name="url"></param> /// <param name="stream"></param> /// <returns></returns> public static async Task DownloadAsync(string url, Stream stream) { #if NET35 || NET40 || NET45 //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); WebClient wc = new WebClient(); var data = await wc.DownloadDataTaskAsync(url).ConfigureAwait(false); await stream.WriteAsync(data, 0, data.Length).ConfigureAwait(false); //foreach (var b in data) //{ // stream.WriteAsync(b); //} #else HttpClient httpClient = SenparcDI.GetRequiredService <SenparcHttpClient>().Client; var data = await httpClient.GetByteArrayAsync(url).ConfigureAwait(false); await stream.WriteAsync(data, 0, data.Length).ConfigureAwait(false); #endif }
/// <summary> /// 使用Post方法上传数据并下载文件或结果 /// </summary> /// <param name="url"></param> /// <param name="data"></param> /// <param name="stream"></param> public static void Download(string url, string data, Stream stream) { #if NET35 || NET40 || NET45 WebClient wc = new WebClient(); var file = wc.UploadData(url, "POST", Encoding.UTF8.GetBytes(string.IsNullOrEmpty(data) ? "" : data)); stream.Write(file, 0, file.Length); //foreach (var b in file) //{ // stream.WriteByte(b); //} #else HttpClient httpClient = SenparcDI.GetRequiredService <SenparcHttpClient>().Client; HttpContent hc = new StringContent(data); var ht = httpClient.PostAsync(url, hc); ht.Wait(); var ft = ht.Result.Content.ReadAsByteArrayAsync(); ft.Wait(); var file = ft.Result; stream.Write(file, 0, file.Length); #endif }
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 override TSenparcEntities GetDbContextInstance(DbContextOptions <TSenparcEntities> dbContextOptions) { //获取 XncfDatabase 对象 //var databaseRegister = Activator.CreateInstance(typeof(TXncfDatabaseRegister)) as TXncfDatabaseRegister; //获取当前适用的 DbContext 类型 var dbContextType = MultipleDatabasePool.Instance.GetXncfDbContextType(typeof(TXncfDatabaseRegister)); var constructorParams = new List <object>() { dbContextOptions }; //判断构造函数参数个数 if (dbContextType.GetConstructors().First().GetParameters().Length == 2) { constructorParams.Add(SenparcDI.GetServiceProvider());//添加第二个参数(目前只为系统基础对象,如 SystemServiceEntities 使用) } //获取 XncfSenparcEntities 实例 var xncfSenparcEntities = Activator.CreateInstance(dbContextType, constructorParams.ToArray()) as TSenparcEntities; return(xncfSenparcEntities); }
/// <summary> /// 注册列表 /// </summary> /// <param name="serverlist">Key:服务器地址(通常为IP),Value:端口</param> public static void RegisterServerList(string configurationString) { if (!string.IsNullOrEmpty(configurationString)) { var dic = new Dictionary <string, int>(); var servers = configurationString.Split(';'); foreach (var server in servers) { try { var serverData = server.Split(':'); dic[serverData[0]] = int.Parse(serverData[1]); } catch (Exception ex) { Senparc.CO2NET.Trace.SenparcTrace.BaseExceptionLog(new CacheException(ex.Message, ex)); } } #if !NET45 if (dic.Count() > 0) { SenparcDI.GetServiceCollection().AddSenparcMemcached(options => { foreach (var item in dic) { options.AddServer(item.Key, item.Value); } }); } #endif RegisterServerList(dic); } }
/// <summary> /// 操作列队 /// </summary> public static void OperateQueue() { lock (FlushCacheLock) { var mq = new OperationQueue(); var key = mq.GetCurrentKey(); //获取最新的Key var serviceProvider = SenparcDI.GetServiceProvider(); while (!string.IsNullOrEmpty(key)) { try { var operationQueueService = serviceProvider.GetService <OperationQueueService>(); var mqItem = mq.GetItem(key); //获取任务项 //识别类型 switch (mqItem.OperationQueueType) { case OperationQueueType.更新用户头像: operationQueueService.UpdateAccountHeadImgAsync(serviceProvider, (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 } } }
//#if !NET35 && !NET40 /// <summary> /// 从Url下载,并保存到指定目录 /// </summary> /// <param name="url">需要下载文件的Url</param> /// <param name="filePathName">保存文件的路径,如果下载文件包含文件名,按照文件名储存,否则将分配Ticks随机文件名</param> /// <param name="timeOut">超时时间</param> /// <returns></returns> public static string Download(string url, string filePathName, int timeOut = 999) { var dir = Path.GetDirectoryName(filePathName) ?? "/"; Directory.CreateDirectory(dir); #if NET35 || NET40 || NET45 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; request.Timeout = timeOut; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (Stream responseStream = response.GetResponseStream()) { string responseFileName = null; var contentDescriptionHeader = response.GetResponseHeader("Content-Disposition"); if (!string.IsNullOrEmpty(contentDescriptionHeader)) { var fileName = Regex.Match(contentDescriptionHeader, @"(?<=filename="")([\s\S]+)(?= "")", RegexOptions.IgnoreCase).Value; responseFileName = Path.Combine(dir, fileName); } var fullName = responseFileName ?? Path.Combine(dir, GetRandomFileName()); using (var fs = File.Open(filePathName, FileMode.OpenOrCreate)) { byte[] bArr = new byte[1024]; int size = responseStream.Read(bArr, 0, (int)bArr.Length); while (size > 0) { fs.Write(bArr, 0, size); fs.Flush(); size = responseStream.Read(bArr, 0, (int)bArr.Length); } } return(fullName); } #else System.Net.Http.HttpClient httpClient = SenparcDI.GetRequiredService <SenparcHttpClient>().Client; using (var responseMessage = httpClient.GetAsync(url).Result) { if (responseMessage.StatusCode == HttpStatusCode.OK) { string responseFileName = null; //ContentDisposition可能会为Null if (responseMessage.Content.Headers.ContentDisposition != null && responseMessage.Content.Headers.ContentDisposition.FileName != null && responseMessage.Content.Headers.ContentDisposition.FileName != "\"\"") { responseFileName = Path.Combine(dir, responseMessage.Content.Headers.ContentDisposition.FileName.Trim('"')); } var fullName = responseFileName ?? Path.Combine(dir, GetRandomFileName()); using (var fs = File.Open(fullName, FileMode.Create)) { using (var responseStream = responseMessage.Content.ReadAsStreamAsync().Result) { responseStream.CopyTo(fs); fs.Flush(); } } return(fullName); } else { return(null); } } #endif }
public ServiceBase(IRepositoryBase <T> repo, IMapper mapper = null) : base(repo) { RepositoryBase = repo; Mapper = mapper == null?SenparcDI.GetService <IMapper>() : mapper;//确保 Mapper 中有值 }
/// <summary> /// 注册TenPayV3Info信息 /// </summary> /// <param name="tenPayV3Info"></param> /// <param name="name">公众号唯一标识(或名称)</param> public static void Register(TenPayV3Info tenPayV3Info, string name) { var key = GetKey(tenPayV3Info.MchId, tenPayV3Info.Sub_MchId); Data[key] = tenPayV3Info; //添加到全局变量 if (!name.IsNullOrEmpty()) { Senparc.Weixin.Config.SenparcWeixinSetting.Items[name].TenPayV3_AppId = tenPayV3Info.AppId; Senparc.Weixin.Config.SenparcWeixinSetting.Items[name].TenPayV3_AppSecret = tenPayV3Info.AppSecret; Senparc.Weixin.Config.SenparcWeixinSetting.Items[name].TenPayV3_MchId = tenPayV3Info.MchId; Senparc.Weixin.Config.SenparcWeixinSetting.Items[name].TenPayV3_Key = tenPayV3Info.Key; Senparc.Weixin.Config.SenparcWeixinSetting.Items[name].TenPayV3_CertPath = tenPayV3Info.CertPath; Senparc.Weixin.Config.SenparcWeixinSetting.Items[name].TenPayV3_CertSecret = tenPayV3Info.CertSecret; Senparc.Weixin.Config.SenparcWeixinSetting.Items[name].TenPayV3_TenpayNotify = tenPayV3Info.TenPayV3Notify; Senparc.Weixin.Config.SenparcWeixinSetting.Items[name].TenPayV3_WxOpenTenpayNotify = tenPayV3Info.TenPayV3_WxOpenNotify; Senparc.Weixin.Config.SenparcWeixinSetting.Items[name].TenPayV3_SubMchId = tenPayV3Info.Sub_MchId; Senparc.Weixin.Config.SenparcWeixinSetting.Items[name].TenPayV3_SubAppId = tenPayV3Info.Sub_AppId; Senparc.Weixin.Config.SenparcWeixinSetting.Items[name].TenPayV3_SubAppSecret = tenPayV3Info.Sub_AppSecret; } //进行证书注册 #if NETSTANDARD2_0 || NETCOREAPP3_0 try { var service = SenparcDI.GlobalServiceCollection; var certName = key; var certPassword = tenPayV3Info.CertSecret; var certPath = tenPayV3Info.CertPath; //添加注册 //service.AddSenparcHttpClientWithCertificate(certName, certPassword, certPath, false); #region 测试添加证书 //添加注册 if (!string.IsNullOrEmpty(certPath)) { if (File.Exists(certPath)) { try { var cert = new X509Certificate2(certPath, certPassword, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet); var checkValidationResult = false; var serviceCollection = SenparcDI.GlobalServiceCollection; //serviceCollection.AddHttpClient<SenparcHttpClient>(certName) serviceCollection.AddHttpClient(certName) .ConfigurePrimaryHttpMessageHandler(() => { var httpClientHandler = HttpClientHelper.GetHttpClientHandler(null, RequestUtility.SenparcHttpClientWebProxy, System.Net.DecompressionMethods.None); httpClientHandler.ClientCertificates.Add(cert); if (checkValidationResult) { httpClientHandler.ServerCertificateCustomValidationCallback = new Func <HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool>(RequestUtility.CheckValidationResult); } return(httpClientHandler); }); } catch (Exception ex) { Senparc.CO2NET.Trace.SenparcTrace.SendCustomLog($"添加微信支付证书发生异常", $"certName:{certName},certPath:{certPath}"); Senparc.CO2NET.Trace.SenparcTrace.BaseExceptionLog(ex); } } else { Senparc.CO2NET.Trace.SenparcTrace.SendCustomLog($"已设置微信支付证书,但无法找到文件", $"certName:{certName},certPath:{certPath}"); } } #endregion } catch (Exception ex) { throw; } finally { SenparcDI.ResetGlobalIServiceProvider(); } #endif }
/// <summary> /// 点击事件 /// </summary> /// <param name="requestMessage">请求消息</param> /// <returns></returns> public override IResponseMessageBase OnEvent_ClickRequest(RequestMessageEvent_Click requestMessage) { IResponseMessageBase reponseMessage = null; //菜单点击,需要跟创建菜单时的Key匹配 switch (requestMessage.EventKey) { case "OneClick": { //这个过程实际已经在OnTextOrEventRequest中命中“OneClick”关键字,并完成回复,这里不会执行到。 var strongResponseMessage = CreateResponseMessage <ResponseMessageText>(); reponseMessage = strongResponseMessage; strongResponseMessage.Content = "您点击了底部按钮。\r\n为了测试微信软件换行bug的应对措施,这里做了一个——\r\n换行"; } break; case "SubClickRoot_Text": { var strongResponseMessage = CreateResponseMessage <ResponseMessageText>(); reponseMessage = strongResponseMessage; strongResponseMessage.Content = "您点击了子菜单按钮。"; } break; case "SubClickRoot_News": { var strongResponseMessage = CreateResponseMessage <ResponseMessageNews>(); reponseMessage = strongResponseMessage; strongResponseMessage.Articles.Add(new Article() { Title = "您点击了子菜单图文按钮", Description = "您点击了子菜单图文按钮,这是一条图文信息。这个区域是Description内容\r\n可以使用\\r\\n进行换行。", PicUrl = "https://sdk.weixin.senparc.com/Images/qrcode.jpg", Url = "https://sdk.weixin.senparc.com" }); //随机添加一条图文,或只输出一条图文信息 if (SystemTime.Now.Second % 2 == 0) { strongResponseMessage.Articles.Add(new Article() { Title = "这是随机产生的第二条图文信息,用于测试多条图文的样式", Description = "这是随机产生的第二条图文信息,用于测试多条图文的样式", PicUrl = "https://sdk.weixin.senparc.com/Images/qrcode.jpg", Url = "https://sdk.weixin.senparc.com" }); } } break; case "SubClickRoot_Music": { //上传缩略图 #if NET45 var filePath = "~/Images/Logo.thumb.jpg"; #else var filePath = "~/wwwroot/Images/Logo.thumb.jpg"; #endif var uploadResult = Senparc.Weixin.MP.AdvancedAPIs.MediaApi.UploadTemporaryMedia(appId, Senparc.Weixin.MP.UploadMediaFileType.thumb, ServerUtility.ContentRootMapPath(filePath)); //PS:缩略图官方没有特别提示文件大小限制,实际测试哪怕114K也会返回文件过大的错误,因此尽量控制在小一点(当前图片39K) //设置音乐信息 var strongResponseMessage = CreateResponseMessage <ResponseMessageMusic>(); reponseMessage = strongResponseMessage; strongResponseMessage.Music.Title = "天籁之音"; strongResponseMessage.Music.Description = "真的是天籁之音"; strongResponseMessage.Music.MusicUrl = "https://sdk.weixin.senparc.com/Content/music1.mp3"; strongResponseMessage.Music.HQMusicUrl = "https://sdk.weixin.senparc.com/Content/music1.mp3"; strongResponseMessage.Music.ThumbMediaId = uploadResult.thumb_media_id; } break; case "SubClickRoot_Image": { //上传图片 #if NET45 var filePath = "~/Images/Logo.jpg"; #else var filePath = "~/wwwroot/Images/Logo.jpg"; #endif var uploadResult = Senparc.Weixin.MP.AdvancedAPIs.MediaApi.UploadTemporaryMedia(appId, Senparc.Weixin.MP.UploadMediaFileType.image, ServerUtility.ContentRootMapPath(filePath)); //设置图片信息 var strongResponseMessage = CreateResponseMessage <ResponseMessageImage>(); reponseMessage = strongResponseMessage; strongResponseMessage.Image.MediaId = uploadResult.media_id; } break; case "SendMenu": //菜单消息 { //注意: //1、此接口可以在任意地方调用(包括后台线程),此处演示为通过 //2、一下"s:"前缀只是 Senparc.Weixin 的内部约定,可以使用 OnTextRequest事件中的 requestHandler.SelectMenuKeyword() 方法自动匹配到后缀(如101) var menuContentList = new List <SendMenuContent>() { new SendMenuContent("101", "满意"), new SendMenuContent("102", "一般"), new SendMenuContent("103", "不满意") }; //使用异步接口 CustomApi.SendMenuAsync(appId, OpenId, "请对 Senparc.Weixin SDK 给出您的评价", menuContentList, "感谢您的参与!"); reponseMessage = new ResponseMessageNoResponse(); //不返回任何消息 } break; case "SubClickRoot_Agent": //代理消息 { //获取返回的XML var dt1 = SystemTime.Now; reponseMessage = MessageAgent.RequestResponseMessage(this, SenparcDI.GetServiceProvider(), agentUrl, agentToken, RequestDocument.ToString()); //上面的方法也可以使用扩展方法:this.RequestResponseMessage(this,agentUrl, agentToken, RequestDocument.ToString()); var dt2 = SystemTime.Now; if (reponseMessage is ResponseMessageNews) { (reponseMessage as ResponseMessageNews) .Articles[0] .Description += string.Format("\r\n\r\n代理过程总耗时:{0}毫秒", (dt2 - dt1).Milliseconds); } } break; case "Member": //托管代理会员信息 { //原始方法为:MessageAgent.RequestXml(this,agentUrl, agentToken, RequestDocument.ToString());//获取返回的XML reponseMessage = this.RequestResponseMessage(SenparcDI.GetServiceProvider(), agentUrl, agentToken, RequestDocument.ToString()); } break; case "OAuth": //OAuth授权测试 { var strongResponseMessage = CreateResponseMessage <ResponseMessageNews>(); strongResponseMessage.Articles.Add(new Article() { Title = "OAuth2.0测试", Description = "选择下面两种不同的方式进行测试,区别在于授权成功后,最后停留的页面。", //Url = "https://sdk.weixin.senparc.com/oauth2", //PicUrl = "https://sdk.weixin.senparc.com/Images/qrcode.jpg" }); strongResponseMessage.Articles.Add(new Article() { Title = "OAuth2.0测试(不带returnUrl),测试环境可使用", Description = "OAuth2.0测试(不带returnUrl)", Url = "https://sdk.weixin.senparc.com/oauth2", PicUrl = "https://sdk.weixin.senparc.com/Images/qrcode.jpg" }); var returnUrl = "/OAuth2/TestReturnUrl"; strongResponseMessage.Articles.Add(new Article() { Title = "OAuth2.0测试(带returnUrl),生产环境强烈推荐使用", Description = "OAuth2.0测试(带returnUrl)", Url = "https://sdk.weixin.senparc.com/oauth2?returnUrl=" + returnUrl.UrlEncode(), PicUrl = "https://sdk.weixin.senparc.com/Images/qrcode.jpg" }); reponseMessage = strongResponseMessage; } break; case "Description": { var strongResponseMessage = CreateResponseMessage <ResponseMessageText>(); strongResponseMessage.Content = GetWelcomeInfo(); reponseMessage = strongResponseMessage; } break; case "SubClickRoot_PicPhotoOrAlbum": { var strongResponseMessage = CreateResponseMessage <ResponseMessageText>(); reponseMessage = strongResponseMessage; strongResponseMessage.Content = "您点击了【微信拍照】按钮。系统将会弹出拍照或者相册发图。"; } break; case "SubClickRoot_ScancodePush": { var strongResponseMessage = CreateResponseMessage <ResponseMessageText>(); reponseMessage = strongResponseMessage; strongResponseMessage.Content = "您点击了【微信扫码】按钮。"; } break; case "ConditionalMenu_Male": { var strongResponseMessage = CreateResponseMessage <ResponseMessageText>(); reponseMessage = strongResponseMessage; strongResponseMessage.Content = "您点击了个性化菜单按钮,您的微信性别设置为:男。"; } break; case "ConditionalMenu_Femle": { var strongResponseMessage = CreateResponseMessage <ResponseMessageText>(); reponseMessage = strongResponseMessage; strongResponseMessage.Content = "您点击了个性化菜单按钮,您的微信性别设置为:女。"; } break; case "GetNewMediaId": //获取新的MediaId { var strongResponseMessage = CreateResponseMessage <ResponseMessageText>(); try { var result = Senparc.Weixin.MP.AdvancedAPIs.MediaApi.UploadForeverMedia(appId, ServerUtility.ContentRootMapPath("~/Images/logo.jpg")); strongResponseMessage.Content = result.media_id; } catch (Exception e) { strongResponseMessage.Content = "发生错误:" + e.Message; Senparc.Weixin.WeixinTrace.SendCustomLog("调用UploadForeverMedia()接口发生异常", e.Message); } } break; default: { var strongResponseMessage = CreateResponseMessage <ResponseMessageText>(); strongResponseMessage.Content = "您点击了按钮,EventKey:" + requestMessage.EventKey; reponseMessage = strongResponseMessage; } break; } return(reponseMessage); }
/// <summary> /// 给.NET Core使用的HttpPost请求公共设置方法 /// </summary> /// <param name="url"></param> /// <param name="hc"></param> /// <param name="cookieContainer"></param> /// <param name="postStream"></param> /// <param name="fileDictionary"></param> /// <param name="refererUrl"></param> /// <param name="encoding"></param> /// <param name="cer"></param> /// <param name="useAjax"></param> /// <param name="headerAddition">header附加信息</param> /// <param name="timeOut"></param> /// <param name="checkValidationResult"></param> /// <param name="contentType"></param> /// <returns></returns> public static HttpClient HttpPost_Common_NetCore(string url, out HttpContent hc, CookieContainer cookieContainer = null, Stream postStream = null, Dictionary <string, string> fileDictionary = null, string refererUrl = null, Encoding encoding = null, X509Certificate2 cer = null, bool useAjax = false, Dictionary <string, string> headerAddition = null, int timeOut = Config.TIME_OUT, bool checkValidationResult = false, string contentType = HttpClientHelper.DEFAULT_CONTENT_TYPE) { HttpClientHandler handler = HttpClientHelper.GetHttpClientHandler(cookieContainer, SenparcHttpClientWebProxy, DecompressionMethods.GZip); if (checkValidationResult) { handler.ServerCertificateCustomValidationCallback = new Func <HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool>(CheckValidationResult); } if (cer != null) { handler.ClientCertificates.Add(cer); } var senparcHttpClient = SenparcDI.GetRequiredService <SenparcHttpClient>(); senparcHttpClient.SetCookie(new Uri(url), cookieContainer);//设置Cookie HttpClient client = senparcHttpClient.Client; HttpClientHeader(client, refererUrl, useAjax, headerAddition, timeOut); #region 处理Form表单文件上传 var formUploadFile = fileDictionary != null && fileDictionary.Count > 0;//是否用Form上传文件 if (formUploadFile) { contentType = "multipart/form-data"; //通过表单上传文件 string boundary = "----" + SystemTime.Now.Ticks.ToString("x"); var multipartFormDataContent = new MultipartFormDataContent(boundary); hc = multipartFormDataContent; foreach (var file in fileDictionary) { try { var fileName = file.Value; //准备文件流 using (var fileStream = FileHelper.GetFileStream(fileName)) { if (fileStream != null) { //存在文件 var memoryStream = new MemoryStream(); fileStream.CopyTo(memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); //multipartFormDataContent.Add(new StreamContent(memoryStream), file.Key, Path.GetFileName(fileName)); //报流已关闭的异常 multipartFormDataContent.Add(CreateFileContent(memoryStream, file.Key, Path.GetFileName(fileName)), file.Key, Path.GetFileName(fileName)); fileStream.Dispose(); } else { //不存在文件或只是注释 multipartFormDataContent.Add(new StringContent(file.Value), "\"" + file.Key + "\""); } } } catch (Exception ex) { throw ex; } } hc.Headers.ContentType = MediaTypeHeaderValue.Parse(string.Format("multipart/form-data; boundary={0}", boundary)); } else { if (postStream.Length > 0) { if (contentType == HttpClientHelper.DEFAULT_CONTENT_TYPE) { //如果ContentType是默认值,则设置成为二进制流 contentType = "application/octet-stream"; } //contentType = "application/x-www-form-urlencoded"; } hc = new StreamContent(postStream); hc.Headers.ContentType = new MediaTypeHeaderValue(contentType); //使用Url格式Form表单Post提交的时候才使用application/x-www-form-urlencoded //去掉注释以测试Request.Body为空的情况 //hc.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); } //HttpContentHeader(hc, timeOut); #endregion if (!string.IsNullOrEmpty(refererUrl)) { client.DefaultRequestHeaders.Referrer = new Uri(refererUrl); } return(client); }