/// <summary> /// 获取数据 /// </summary> /// <returns></returns> public BaseResult <UserInfo> Get(int id) { var result = new BaseResult <UserInfo>(); try { //数据库交互处理… //模拟数据 var r = _schoolInfoService.Get("0591001"); if (r.Code != 200) { result.SetError(r.Msg, r.Code); return(result); } var userInfo = new UserInfo { UserName = "******", Tel = "13556598568", Address = "福建福州", Email = "13556598568.qq.com", SchoolName = r.Result.SchoolName }; result.Result = userInfo; result.Msg = "获取成功!"; return(result); } catch (Exception ex) { result.SetError(ex.Message, 5000); return(result); } }
public BaseResult <LoginResponse> Login(LoginRequest request) { var result = new BaseResult <LoginResponse>(); try { if (string.IsNullOrEmpty(request.UserName)) { result.SetError("用户名不能为空", BaseStateCode.参数不能为空); return(result); } if (string.IsNullOrEmpty(request.UserPsw)) { result.SetError("密码不能为空", BaseStateCode.参数不能为空); return(result); } /*…这边省略登入业务代码…*/ var response = new LoginResponse { UserName = request.UserName, Token = Guid.NewGuid().ToString("N") }; result.SetOkResult(response, "登入成功"); return(result); } catch (Exception ex) { var errorCode = Guid.NewGuid().ToString("N"); //这边用errorCode作为日志主键,把错误信息写入到日志 var errorMessage = errorCode.ToMsgException(); result.SetError(errorMessage, BaseStateCode.TryCatch异常错误); return(result); } }
// GET: Yzm /// <summary> /// 验证码识别 /// </summary> /// <param name="base64">含验证码的页面全屏截图</param> /// <param name="x">验证码x</param> /// <param name="y">验证码y</param> /// <param name="width">验证码width</param> /// <param name="height">验证码height</param> /// <returns></returns> public JsonResult Index(string base64, int x = 0, int y = 0, int width = 0, int height = 0) { BaseResult <string> result = new BaseResult <string>() { Result = "" }; if (string.IsNullOrEmpty(base64)) { result.SetError("参数base64不能为空"); return(Json(result, JsonRequestBehavior.AllowGet)); } try { var fullPageBytes = Convert.FromBase64String(base64); var imageDir = Server.MapPath("~/App_Data/"); const string fileSuffix = ".png"; var fileName = Guid.NewGuid().ToString().Replace("-", ""); var screenImagePath = imageDir + fileName + fileSuffix; var image = ImageHelper.BytesToImage(fullPageBytes); //计算出元素上、下、左、右 位置 var left = x; var top = y; var right = width; var bottom = height; //定义截取矩形 var cropArea = new Rectangle(left, top, right, bottom); //要截取的区域大小 var screenImage = (Bitmap)image; //进行裁剪 var bmpCrop = screenImage.Clone(cropArea, screenImage.PixelFormat); //保存成新文件 bmpCrop.Save(screenImagePath); //释放对象 screenImage.Dispose(); bmpCrop.Dispose(); //var screenImagePath= imageDir+"111.jpg"; var yzm = new YzmService(); result.Result = yzm.RecognizeLocal(screenImagePath); return(Json(result, JsonRequestBehavior.AllowGet)); } catch (Exception ex) { result.SetError(ex.Message); return(Json(result, JsonRequestBehavior.AllowGet)); } }
/// <summary> /// 调用自定义机器人发整体跳转ActionCard类型消息 /// </summary> /// <param name="webhook">webHook地址</param> /// <param name="title">消息标题</param> /// <param name="markdownMessages">消息内容</param> /// <param name="hideAvatar">0-正常发消息者头像,1-隐藏发消息者头像</param> /// <param name="btnOrientation">0-按钮竖直排列,1-按钮横向排列</param> /// <param name="singleTitle">单个按钮的方案。(设置此项和singleUrl后btns无效。)</param> /// <param name="singleUrl">点击singleTitle按钮触发的URL</param> /// <returns></returns> public static BaseResult <object> SendActionCardMessage(string webhook, string title, List <MarkdownMessage> markdownMessages, int hideAvatar, int btnOrientation, string singleTitle, string singleUrl) { var result = new BaseResult <object>(); try { object message = new { msgtype = "actionCard", actionCard = new { title = title, text = RestructureMessage(markdownMessages), hideAvatar = hideAvatar, btnOrientation = btnOrientation, singleTitle = singleTitle, singleURL = singleUrl }, }; return(SendMessage(webhook, message)); } catch (Exception ex) { result.SetError(ex.Message); return(result); } }
/// <summary> /// 调用自定义机器人发独立跳转ActionCard类型消息 /// </summary> /// <param name="webhook">webHook地址</param> /// <param name="title">消息标题</param> /// <param name="markdownMessages">消息内容</param> /// <param name="hideAvatar">0-正常发消息者头像,1-隐藏发消息者头像</param> /// <param name="btnOrientation">0-按钮竖直排列,1-按钮横向排列</param> /// <param name="btns">按钮集合</param> /// <returns></returns> public static BaseResult <object> SendSingleActionCardMessage(string webhook, string title, List <MarkdownMessage> markdownMessages, int hideAvatar, int btnOrientation, List <Btn> btns) { var result = new BaseResult <object>(); try { var btnObjs = new List <object>(); if (btns != null && btns.Count > 0) { foreach (var item in btns) { object obj = new { title = item.Title, actionURL = item.ActionUrl }; btnObjs.Add(obj); } } object message = new { actionCard = new { title = title, text = RestructureMessage(markdownMessages), hideAvatar = hideAvatar, btnOrientation = btnOrientation, btns = btnObjs }, msgtype = "actionCard", }; return(SendMessage(webhook, message)); } catch (Exception ex) { result.SetError(ex.Message); return(result); } }
/// <summary> /// 结束指定的windows进程如果进程存在 /// </summary> /// <param name="processName">进程名称,不包含扩展名</param> /// <param name="processFileName">进程文件完整路径,如果为空则删除所有进程名为processName参数值的进程</param> public static BaseResult <string> KillProcess(string processName, string processFileName) { var result = new BaseResult <string>(); try { var processes = Process.GetProcessesByName(processName); foreach (var p in processes) { if (!string.IsNullOrEmpty(processFileName)) { if (p.MainModule == null || processFileName != p.MainModule.FileName) { continue; } p.Kill(); p.Close(); } else { p.Kill(); p.Close(); } } result.Msg = "成功结束进程!"; return(result); } catch (Exception ex) { result.SetError($"结束指定的Widnows进程异常:{ex.Message}", 5000); return(result); } }
/// <summary> /// 调用自定义机器人发Text类型消息 /// </summary> /// <param name="webhook">webHook地址</param> /// <param name="content">消息内容</param> /// <param name="atMobiles">被@人的手机号</param> /// <param name="isAtAll">@所有人时:true,否则为:false</param> /// <returns></returns> public static BaseResult <object> SendTextMessage(string webhook, string content, List <string> atMobiles, bool isAtAll) { var result = new BaseResult <object>(); try { //@手机号 var mobiles = ""; if (!isAtAll) { mobiles = GetAtMobiles(atMobiles); } //消息内容 object message = new { msgtype = "text", text = new { content = (content + mobiles).Trim(), }, at = new { atMobiles = atMobiles, isAtAll = isAtAll } }; return(SendMessage(webhook, message)); } catch (Exception ex) { result.SetError(ex.Message); return(result); } }
/// <summary> /// 调用自定义机器人发FeedCard类型消息 /// </summary> /// <param name="webhook">webHook地址</param> /// <param name="links">图片按钮集合</param> /// <returns></returns> public static BaseResult <object> SendFeedCardMessage(string webhook, List <Link> links) { var result = new BaseResult <object>(); try { var linkObjs = new List <object>(); if (links != null && links.Count > 0) { foreach (var item in links) { object obj = new { title = item.Title, messageURL = item.MessageUrl, picURL = item.PicUrl }; linkObjs.Add(obj); } } object message = new { feedCard = new { links = linkObjs, }, msgtype = "feedCard" }; return(SendMessage(webhook, message)); } catch (Exception ex) { result.SetError(ex.Message); return(result); } }
/// <summary> /// 调用自定义机器人发Link类型消息 /// </summary> /// <param name="webhook">webHook地址</param> /// <param name="title">消息标题</param> /// <param name="text">消息内容(注:如果太长只会部分展示)</param> /// <param name="picUrl">图片url</param> /// <param name="messageUrl">点击消息跳转的url</param> /// <returns></returns> public static BaseResult <object> SendLinkMessage(string webhook, string title, string text, string picUrl, string messageUrl) { var result = new BaseResult <object>(); try { object message = new { msgtype = "link", link = new { title = title, text = text, picUrl = picUrl, messageUrl = messageUrl }, }; return(SendMessage(webhook, message)); } catch (Exception ex) { result.SetError(ex.Message); return(result); } }
/// <summary> /// Post请求 /// </summary> /// <param name="address">请求地址</param> /// <param name="parameters">请求参数</param> /// <param name="dateTimeFormat">返回的时间格式</param> /// <returns></returns> private BaseResult <T> PostRequest <T>(string address, object parameters, string dateTimeFormat = "yyyy-MM-dd HH:mm:ss") where T : class { var result = new BaseResult <T>(); try { if (string.IsNullOrEmpty(address)) { result.SetError("address不能为空!"); return(result); } Headers.Add("Content-Type", "application/json;charset=UTF-8"); var @params = JsonConvert.SerializeObject(parameters); @params = Regex.Replace(@params, @"\\/Date\((\d+)\)\\/", match => { var dt = new DateTime(1970, 1, 1); dt = dt.AddMilliseconds(long.Parse(match.Groups[1].Value)); dt = dt.ToLocalTime(); return(dt.ToString(dateTimeFormat)); }); var dataBytes = new byte[0]; if (!string.IsNullOrEmpty(@params)) { dataBytes = Encoding.GetBytes(@params); } var bytes = UploadData(address, HttpMethod.Post.ToString(), dataBytes); var content = Encoding.GetString(bytes); if (string.IsNullOrEmpty(content)) { return(result); } if (typeof(T) == typeof(string)) { result.Result = (T)Convert.ChangeType(content, typeof(T)); return(result); } result.Result = JsonConvert.DeserializeObject <T>(content); return(result); } catch (Exception ex) { result.SetError(ex.Message, BaseStateCode.TryCatch异常错误); return(result); } }
/// <summary> /// 执行HTTP GET请求 /// </summary> /// <param name="url">地址</param> /// <param name="parameters">参数</param> /// <param name="cookieContainer">CookieContainer</param> /// <param name="proxy">代理请求信息</param> /// <param name="rspEncoding">响应编码</param> public BaseResult <string> DoGet(string url, IDictionary <string, string> parameters, CookieContainer cookieContainer, WebProxy proxy = null, Encoding rspEncoding = null) { BaseResult <string> result = new BaseResult(); HttpWebRequest httpWebRequest = null; HttpWebResponse httpWebResponse = null; if (rspEncoding == null) { rspEncoding = Encoding.GetEncoding("UTF-8"); } try { //参数不为空 if (parameters != null) { if (!string.IsNullOrEmpty(url)) { var urlArray = url.Split('?'); url = $"{urlArray[0]}?{BuildQuery(parameters)}"; } } httpWebRequest = GetWebRequest(url, "GET"); //cookie if (cookieContainer != null) { httpWebRequest.CookieContainer = cookieContainer; } //代理请求 if (proxy != null) { httpWebRequest.Proxy = proxy; } httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); var responseStream = httpWebResponse.GetResponseStream(); if (responseStream != null) { var streamReader = new StreamReader(responseStream, rspEncoding); var html = streamReader.ReadToEnd(); streamReader.Close(); responseStream.Close(); result.Result = html; return(result); } result.Result = string.Empty; return(result); } catch (Exception ex) { result.SetError(ex.Message, 5000); return(result); } finally { httpWebRequest?.Abort(); httpWebResponse?.Close(); } }
/// <summary> /// 执行HTTP POST请求 /// </summary> /// <param name="url">请求地址</param> /// <param name="parameters">参数</param> /// <param name="cookieContainer">CookieContainer</param> /// <param name="proxy">代理请求信息</param> /// <param name="rspEncoding">响应编码</param> public BaseResult <string> DoPost(string url, IDictionary <string, string> parameters, CookieContainer cookieContainer, WebProxy proxy = null, Encoding rspEncoding = null) { BaseResult <string> result = new BaseResult(); HttpWebRequest httpWebRequest = null; HttpWebResponse httpWebResponse = null; if (rspEncoding == null) { rspEncoding = Encoding.GetEncoding("UTF-8"); } try { httpWebRequest = GetWebRequest(url, "POST"); //cookie if (cookieContainer != null) { httpWebRequest.CookieContainer = cookieContainer; } //代理请求 if (proxy != null) { httpWebRequest.Proxy = proxy; } //参数不为空 if (parameters != null) { var byteRequest = Encoding.Default.GetBytes(BuildQuery(parameters)); httpWebRequest.ContentLength = byteRequest.Length; var stream = httpWebRequest.GetRequestStream(); stream.Write(byteRequest, 0, byteRequest.Length); stream.Close(); } httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); var responseStream = httpWebResponse.GetResponseStream(); if (responseStream != null) { var streamReader = new StreamReader(responseStream, rspEncoding); var html = streamReader.ReadToEnd(); streamReader.Close(); responseStream.Close(); result.Result = html; return(result); } result.Result = string.Empty; return(result); } catch (Exception ex) { result.SetError(ex.Message, 5000); return(result); } finally { httpWebRequest?.Abort(); httpWebResponse?.Close(); } }
/// <summary> /// Post请求 /// </summary> /// <param name="address">请求地址</param> /// <param name="parameters">请求参数</param> /// <returns></returns> private BaseResult <T> PostRequest <T>(string address, Dictionary <string, string> parameters) where T : class { var result = new BaseResult <T>(); try { if (string.IsNullOrEmpty(address)) { result.SetError("address不能为空!"); return(result); } var(item1, item2) = BuildUrlParameter(address, parameters); address = item1; var dataBytes = new byte[0]; if (!string.IsNullOrEmpty(item2)) { dataBytes = Encoding.GetBytes(item2); } var bytes = UploadData(address, HttpMethod.Post.ToString(), dataBytes); var content = Encoding.GetString(bytes); if (string.IsNullOrEmpty(content)) { return(result); } if (typeof(T) == typeof(string)) { result.Result = (T)Convert.ChangeType(content, typeof(T)); return(result); } result.Result = JsonConvert.DeserializeObject <T>(content); return(result); } catch (Exception ex) { result.SetError(ex.Message, BaseStateCode.TryCatch异常错误); return(result); } }
/// <summary> /// 执行HTTP POST请求 /// </summary> /// <typeparam name="T">返回类型</typeparam> /// <param name="url">请求地址</param> /// <param name="parameters">参数</param> /// <param name="rspEncoding">响应编码</param> /// <param name="dateTimeFormat">参数时间格式</param> /// <returns></returns> public BaseResult <T> DoPost <T>(string url, object parameters, Encoding rspEncoding = null, string dateTimeFormat = "yyyy-MM-dd HH:mm:ss") { BaseResult <T> result = new BaseResult <T>(); HttpWebRequest httpWebRequest = null; HttpWebResponse httpWebResponse = null; if (rspEncoding == null) { rspEncoding = Encoding.GetEncoding("UTF-8"); } try { httpWebRequest = GetWebRequest(url, "POST"); var @params = JsonConvert.SerializeObject(parameters); @params = Regex.Replace(@params, @"\\/Date\((\d+)\)\\/", match => { var dt = new DateTime(1970, 1, 1); dt = dt.AddMilliseconds(long.Parse(match.Groups[1].Value)); dt = dt.ToLocalTime(); return(dt.ToString(dateTimeFormat)); }); var reqStreamWriter = new StreamWriter(httpWebRequest.GetRequestStream()); reqStreamWriter.Write(@params); reqStreamWriter.Close(); httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); var responseStream = httpWebResponse.GetResponseStream(); if (responseStream != null) { var streamReader = new StreamReader(responseStream, rspEncoding); var html = streamReader.ReadToEnd(); streamReader.Close(); responseStream.Close(); result.Result = JsonConvert.DeserializeObject <T>(html); return(result); } result.Result = default; return(result); } catch (Exception ex) { result.SetError(ex.Message, 5000); return(result); } finally { httpWebRequest?.Abort(); httpWebResponse?.Close(); } }
/// <summary> /// 调用自定义机器人发消息 /// </summary> /// <param name="webhook">webHook地址</param> /// <param name="message">消息信息</param> /// <returns></returns> private static BaseResult <object> SendMessage(string webhook, object message) { var result = new BaseResult <object>(); try { var webHelper = new WebHelper(); string tips; result.Result = webHelper.DoPost <object>(webhook, message, out tips); result.Msg = tips; if (tips == "请求成功") { return(result); } result.SetError(tips); return(result); } catch (Exception ex) { result.SetError(ex.Message); return(result); } }
/// <summary> /// 执行HTTP GET请求 /// </summary> /// <param name="url">地址</param> /// <param name="cookieContainer">CookieContainer</param> /// <param name="proxy">代理请求信息</param> /// <param name="rspEncoding">响应编码</param> public BaseResult <string> DoGet(string url, CookieContainer cookieContainer, WebProxy proxy = null, Encoding rspEncoding = null) { BaseResult <string> result = new BaseResult(); HttpWebRequest httpWebRequest = null; HttpWebResponse httpWebResponse = null; if (rspEncoding == null) { rspEncoding = Encoding.GetEncoding("UTF-8"); } try { httpWebRequest = GetWebRequest(url, "GET"); //cookie if (cookieContainer != null) { httpWebRequest.CookieContainer = cookieContainer; } //代理请求 if (proxy != null) { httpWebRequest.Proxy = proxy; } httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); var responseStream = httpWebResponse.GetResponseStream(); if (responseStream != null) { var streamReader = new StreamReader(responseStream, rspEncoding); var html = streamReader.ReadToEnd(); streamReader.Close(); responseStream.Close(); result.Result = html; return(result); } result.Result = string.Empty; return(result); } catch (Exception ex) { result.SetError(ex.Message, 5000); return(result); } finally { httpWebRequest?.Abort(); httpWebResponse?.Close(); } }
/// <summary> /// 保存数据 /// </summary> /// <param name="userInfo">用户信息</param> /// <returns></returns> public BaseResult Save(UserInfo userInfo) { var result = new BaseResult(); try { //数据库交互处理… result.Msg = "保存成功!"; return(result); } catch (Exception ex) { result.SetError(ex.Message, 5000); return(result); } }
/// <summary> /// 删除数据 /// </summary> /// <param name="id">Id</param> /// <returns></returns> public BaseResult Delete(int id) { var result = new BaseResult(); try { //数据库交互处理… result.Msg = "删除成功!"; return(result); } catch (Exception ex) { result.SetError(ex.Message, 5000); return(result); } }
/// <summary> /// 调用自定义机器人发消息 /// </summary> /// <param name="webhook">webHook地址</param> /// <param name="message">消息信息</param> /// <returns></returns> private static BaseResult <object> SendMessage(string webhook, object message) { var result = new BaseResult <object>(); try { var webHelper = new WebHelper(); result = webHelper.DoPost <object>(webhook, message); return(result); } catch (Exception ex) { result.SetError(ex.Message); return(result); } }
/// <summary> /// 执行Dos命令 /// </summary> /// <param name="cmd">Dos命令及参数</param> /// <param name="isShowCmdWindow">是否显示cmd窗口</param> /// <param name="isCloseCmdProcess">执行完毕后是否关闭cmd进程</param> /// <returns></returns> public static BaseResult <string> RunCommand(string cmd, bool isShowCmdWindow, bool isCloseCmdProcess) { var result = new BaseResult <string>(); try { var strBuilder = new StringBuilder(); var p = new Process { StartInfo = { FileName = "cmd", UseShellExecute = false, RedirectStandardInput = true, RedirectStandardOutput = true, CreateNoWindow = !isShowCmdWindow } }; p.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e) { if (!string.IsNullOrEmpty(e.Data)) { strBuilder.Append($"{e.Data}\n"); } }; p.Start(); var cmdWriter = p.StandardInput; p.BeginOutputReadLine(); if (!string.IsNullOrEmpty(cmd)) { cmdWriter.WriteLine(cmd); } cmdWriter.Close(); p.WaitForExit(); result.Result = strBuilder.ToString(); if (isCloseCmdProcess) { p.Close(); } result.Msg = $"成功执行Dos命令[{cmd}]!"; return(result); } catch (Exception ex) { result.SetError($"执行命令失败,请检查输入的命令是否正确:{ex.Message}", 5000); return(result); } }
/// <summary> /// 调用自定义机器人发消息 /// </summary> /// <param name="webhook">webHook地址</param> /// <param name="message">消息信息</param> /// <returns></returns> private static BaseResult <object> SendMessage(string webhook, object message) { var result = new BaseResult <object>(); try { var webHelper = new WebHelper { ContentType = "application/json;charset=utf-8" }; result = webHelper.DoPost <object>(webhook, message); return(result); } catch (Exception ex) { result.SetError(ex.Message); return(result); } }
/// <summary> /// 调用自定义机器人发Markdown类型消息 /// </summary> /// <param name="webhook">webHook地址</param> /// <param name="title">消息标题</param> /// <param name="titleType">标题类型等级</param> /// <param name="markdownMessages">消息内容</param> /// <param name="atMobiles">被@手机号</param> /// <param name="isAtAll">@所有人时:true,否则为:false</param> /// <returns></returns> public static BaseResult <object> SendMarkdownMessage(string webhook, string title, TitleType titleType, List <MarkdownMessage> markdownMessages, List <string> atMobiles, bool isAtAll) { var result = new BaseResult <object>(); try { //@手机号 var mobiles = ""; if (!isAtAll) { mobiles = GetAtMobiles(atMobiles); } //消息内容头部(标题+被@的人;注:自动换行) var textTop = GetContentGrade(titleType, title) + "\n >" + mobiles + "\n >"; //消息内容 var text = textTop + RestructureMessage(markdownMessages); object message = new { msgtype = "markdown", markdown = new { title = title, text = text, }, at = new { atMobiles = atMobiles, isAtAll = isAtAll, } }; return(SendMessage(webhook, message)); } catch (Exception ex) { result.SetError(ex.Message); return(result); } }
/// <summary> /// 获取用户信息 /// </summary> /// <returns></returns> public BaseResult <UserInfo> Get() { var result = new BaseResult <UserInfo>(); LogHelper.Info("我是测试日志"); //查询数据库..... //if (false) //{ // result.SetError("未查询到该条记录"); // return result; //} var r = _payRecordService.GetRecord(); if (r.Code != 200) { result.SetError(r.Msg, r.Code); return(result); } result.Result = new UserInfo { UserName = "******", Mobile = "136xxxxxxxx", Age = 10, PayCount = r.Result }; return(result); }
/// <summary> /// 获取数据 /// </summary> /// <returns></returns> public BaseResult <SchoolInfo> Get(string schoolCode) { var result = new BaseResult <SchoolInfo>(); try { //数据库交互处理… //模拟数据 var schoolInfo = new SchoolInfo { SchoolCode = "0591001", SchoolName = "福州一中", SchoolType = SchoolType.高中 }; result.Result = schoolInfo; result.Msg = "获取成功!"; return(result); } catch (Exception ex) { result.SetError(ex.Message, 5000); return(result); } }
/// <summary> /// Post请求 /// </summary> /// <typeparam name="TP">入参类型</typeparam> /// <typeparam name="T">出参类型</typeparam> /// <param name="method">表示请求的http方法,大写, 如POST、GET、PUT</param> /// <param name="address">请求地址</param> /// <param name="parameters">请求参数</param> /// <param name="dateTimeFormat">入参的时间格式</param> /// <returns></returns> public BaseResult <T> Request <TP, T>(HttpMethod method, string address, TP parameters, string dateTimeFormat = "yyyy-MM-dd HH:mm:ss") where T : class where TP : class, new() { var result = new BaseResult <T>(); try { if (string.IsNullOrEmpty(address)) { result.SetError("address不能为空!"); return(result); } var contentType = Headers["Content-Type"]?.ToLower(); if (contentType == null) { Headers.Add("Content-Type", "application/json"); contentType = Headers["Content-Type"].ToLower(); } byte[] bytes; var @params = JsonConvert.SerializeObject(parameters); @params = Regex.Replace(@params, @"\\/Date\((\d+)\)\\/", match => { var dt = new DateTime(1970, 1, 1); dt = dt.AddMilliseconds(long.Parse(match.Groups[1].Value)); dt = dt.ToLocalTime(); return(dt.ToString(dateTimeFormat)); }); if (method == HttpMethod.Get) { var dicParameters = JsonConvert.DeserializeObject <Dictionary <string, string> >(@params); var(item1, item2) = BuildUrlParameter(address, dicParameters); address = item1; var parametersStr = BuildQuery(item2); if (!string.IsNullOrEmpty(parametersStr)) { address = $"{item1}?{parametersStr}"; } bytes = DownloadData(address); } else if (contentType.Contains("application/json")) { var dataBytes = Encoding.GetBytes(@params); bytes = UploadData(address, HttpMethod.Post.ToString(), dataBytes); } else { var dicParameters = JsonConvert.DeserializeObject <Dictionary <string, string> >(@params); var parametersStr = BuildQuery(dicParameters); var dataBytes = Encoding.GetBytes(parametersStr); bytes = UploadData(address, HttpMethod.Post.ToString(), dataBytes); } var content = Encoding.GetString(bytes); if (string.IsNullOrEmpty(content)) { return(result); } if (typeof(T) == typeof(string)) { result.Result = (T)Convert.ChangeType(content, typeof(T)); return(result); } result.Result = JsonConvert.DeserializeObject <T>(content); return(result); } catch (Exception ex) { if (ex.GetType().Name == "WebException") { var we = (WebException)ex; using var hr = (HttpWebResponse)we.Response; if (hr != null) { var statusCode = (int)hr.StatusCode; var sb = new StringBuilder(); var responseStream = hr.GetResponseStream(); if (responseStream != null) { var sr = new StreamReader(responseStream, Encoding.UTF8); sb.Append(sr.ReadToEnd()); result.SetError($"{sb}", statusCode); return(result); } } } result.SetError(ex.Message, BaseStateCode.TryCatch异常错误); return(result); } finally { QueryString.Clear(); } }
/// <summary> /// 金额转中文大写整数支持到万亿,小数部分支持到分(超过两位将进行Banker舍入法处理) /// </summary> /// <param name="num">需要转换的双精度浮点数</param> /// <returns></returns> public static BaseResult ToCnMoney(double num) { var result = new BaseResult(); try { string[] lsShZ = { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖", "拾" }; string[] lsDwZh = { "元", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟", "万" }; string[] lsDwX = { "角", "分" }; var iXShBool = false; //是否含有小数,默认没有(0则视为没有) var iZhShBool = true; //是否含有整数,默认有(0则视为没有) var numSrX = ""; //小数部分 string numStrDq; //当前的数字字符 var numStrR = ""; //返回的字符串 num = Math.Round(num, 2); //四舍五入取两位 //各种非正常情况处理 if (num < 0) { result.SetError("参数必须大于0", 6010); return(result); } if (num > 9999999999999.99) { result.SetError("参数不能大于9999999999999.99", 6010); return(result); } if (!(num < 0) && !(num > 0)) { result.Result = lsShZ[0]; return(result); } //判断是否有整数 if (num < 1.00) { iZhShBool = false; } var numStr = num.ToString(CultureInfo.InvariantCulture); var numStrZh = numStr; if (numStrZh.Contains(".")) { //分开整数与小数处理 numStrZh = numStr.Substring(0, numStr.IndexOf(".", StringComparison.Ordinal)); numSrX = numStr.Substring((numStr.IndexOf(".", StringComparison.Ordinal) + 1), (numStr.Length - numStr.IndexOf(".", StringComparison.Ordinal) - 1)); iXShBool = true; } if (numSrX == "" || int.Parse(numSrX) <= 0) { //判断是否含有小数部分 iXShBool = false; } if (iZhShBool) { //整数部分处理 numStrZh = StringHelper.CreateInstance().Reverse(numStrZh); //反转字符串 for (int a = 0; a < numStrZh.Length; a++) { //整数部分转换 numStrDq = numStrZh.Substring(a, 1); if (int.Parse(numStrDq) != 0) { numStrR = lsShZ[int.Parse(numStrDq)] + lsDwZh[a] + numStrR; } else if (a == 0 || a == 4 || a == 8) { if (numStrZh.Length > 8 && a == 4) { continue; } numStrR = lsDwZh[a] + numStrR; } else if (int.Parse(numStrZh.Substring(a - 1, 1)) != 0) { numStrR = lsShZ[int.Parse(numStrDq)] + numStrR; } } if (!iXShBool) { result.Result = numStrR + "整"; return(result); } } for (int b = 0; b < numSrX.Length; b++) { //小数部分转换 numStrDq = numSrX.Substring(b, 1); if (int.Parse(numStrDq) != 0) { numStrR += lsShZ[int.Parse(numStrDq)] + lsDwX[b]; } else if (b != 1 && iZhShBool) { numStrR += lsShZ[int.Parse(numStrDq)]; } } result.Result = numStrR; return(result); } catch (Exception ex) { result.SetError(ex.Message, 5000); return(result); } }