常见.NET功能代码汇总
获取缓存:首先从本地缓存获取,如果没有,再去读取分布式缓存
写缓存:同时写本地缓存和分布式缓存
private static T GetGradeCache<T>(string key) where T:struct { MemoryCacheManager localCache = MemoryCacheManager.Instance; if (!localCache.IsSet(key)) { //本地不存在此缓存 T remoteValue = MemCacheManager.Instance.Get<T>(key); if (!ValueType.Equals(remoteValue, default(T))) { //如果远程有 localCache.Set(key, remoteValue, 1); } else { localCache.SetFromSeconds(key, default(T), 10); } return remoteValue; } T value = localCache.Get<T>(key); return value; } private static void SetGradeCache<T>(string key,T Value,int time) where T : struct { MemoryCacheManager localCache = MemoryCacheManager.Instance; localCache.Remove(key); localCache.Set(key, Value, time); MemCacheManager.Instance.Remove(key); MemCacheManager.Instance.Set(key, Value, time); }
有时候,我们需要求相对于当前根目录的相对目录,比如将日志文件存储在站点目录之外,我们可以使用 ../logs/ 的方式:
string vfileName = string.Format("../logs/{0}_{1}_{2}.log", logFileName, System.Environment.MachineName, DateTime.Now.ToString("yyyyMMdd")); string rootPath = HttpContext.Current.Server.MapPath("/"); string targetPath = System.IO.Path.Combine(rootPath, vfileName); string fileName = System.IO.Path.GetFullPath(targetPath); string fileDir = System.IO.Path.GetDirectoryName(fileName); if (!System.IO.Directory.Exists(fileDir)) System.IO.Directory.CreateDirectory(fileDir);
这个代码会在站点目录之外的日志目录,建立一个 代机器名称的按照日期区分的日志文件。
日志文件可能会并发的写入,此时可能会提示“文件被另外一个进程占用”,因此可以多次尝试写入。下面的方法会递归的进行文件写入尝试,如果尝试次数用完才会最终报错。
/// <summary> /// 保存日志文件 /// </summary> /// <param name="logFileName">不带扩展名文件名</param> /// <param name="logText">日志内容</param> /// <param name="tryCount">如果出错的尝试次数,建议不大于100,如果是0则不尝试</param> public static void SaveLog(string logFileName, string logText, int tryCount) { string vfileName = string.Format("..\\logs\\{0}_{1}_{2}.log", logFileName, System.Environment.MachineName, DateTime.Now.ToString("yyyyMMdd")); string rootPath = System.AppDomain.CurrentDomain.BaseDirectory; string targetPath = System.IO.Path.Combine(rootPath, vfileName); string fileName = System.IO.Path.GetFullPath(targetPath); string fileDir = System.IO.Path.GetDirectoryName(fileName); if (!System.IO.Directory.Exists(fileDir)) System.IO.Directory.CreateDirectory(fileDir); try { System.IO.File.AppendAllText(fileName, logText); tryCount = 0; } catch (Exception ex) { if (tryCount > 0) { System.Threading.Thread.Sleep(1000); logText = logText + "\r\nSaveLog,try again times =" + tryCount + " ,Error:" + ex.Message; tryCount--; SaveLog(logFileName, logText, tryCount); } else { throw new Exception("Save log file Error,try count more times!"); } } }
string GetRemoteIP() { string result = HttpContext.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (null == result || result == String.Empty) { result = HttpContext.Request.ServerVariables["REMOTE_ADDR"]; } if (null == result || result == String.Empty) { result = HttpContext.Request.UserHostAddress; } return result;
可以分为3种方式,
1)ASP.NET MVC 在控制器的默认Action里面获取请求其它Action的路径
比如在默认的 Index Action里面获取路径,如下:
string sso_url= "http://" + Request.Url.Authority + Request.Url.AbsolutePath + "/SSO?id=" + userid;
2)在其它Action里面获取当前控制器的路径
string ctrName = RouteData.Values["controller"].ToString(); string redirectUrl = "http://" + Request.Url.Authority + "/" + ctrName + "/SSO?id=" + userid;
3)直接获取当前Action请求的路径
string url=Request.Url.ToString();
需要指定Context的contentType 为“text/plain”,代码如下:
public ActionResult SendMessage() { string txt="你好!"; return Content(text, "text/plain", System.Text.Encoding.UTF8); }
这里主要使用XDocument,XElement对象来操作XML内容,如下代码:
public static class XDocumentExtentsion { //生成XML的申明部分 public static string ToStringWithDeclaration(this XDocument doc, SaveOptions options = SaveOptions.DisableFormatting) { return doc.Declaration.ToString() + doc.ToString(options); } } public string CreateMsgResult(string loginUserId,string corpid, string msg,string ts) { var xDoc = new XDocument( new XDeclaration("1.0", "UTF-8", null), new XElement("result", new XElement("corpid", corpid), new XElement("userid", loginUserId), new XElement("ts", ts), new XElement("sendmsg", msg) )); return xDoc.ToStringWithDeclaration(); } public ResponseMessage ParseXMLString(string xml) { var xDoc = XDocument.Parse(xml); if (xDoc == null) return null; var root = xDoc.Element("result"); if(root==null) throw new Exception ("not found the 'result' root node,input XML\r\n"+xml); ResponseMessage result = new ResponseMessage() { ErrorCode = root.Element("rescode").Value, ErrorMessage = root.Element("resmsg").Value, RedirectUrl = root.Element("redirect_url") == null ? "" : root.Element("redirect_url").Value }; return result; }
使用 HttpWebRequest和HttpWebResponse 对象完成Web访问,如果是.NET 4.5,建议直接使用 HttpClient对象:
/// <summary> /// 获取请求结果 /// </summary> /// <param name="requestUrl">请求地址</param> /// <param name="timeout">超时时间(秒)</param> /// <param name="requestXML">请求xml内容</param> /// <param name="isPost">是否post提交</param> /// <param name="encoding">编码格式 例如:utf-8</param> /// <param name="errorMsg">抛出的错误信息</param> /// <returns>返回请求结果</returns> public static string HttpWebRequest(string requestUrl, int timeout, string requestXML, bool isPost, string encoding, out string errorMsg, string contentType = "application/x-www-form-urlencoded") { errorMsg = string.Empty; string result = string.Empty; try { byte[] bytes = System.Text.Encoding.GetEncoding(encoding).GetBytes(requestXML); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl); request.Referer = requestUrl; request.Method = isPost ? "POST" : "GET"; request.Timeout = timeout * 1000; if (isPost) { request.ContentType = contentType;// "application/x-www-form-urlencoded"; request.ContentLength = bytes.Length; using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(bytes, 0, bytes.Length); requestStream.Close(); } } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream responseStream = response.GetResponseStream(); if (responseStream != null) { StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding(encoding)); result = reader.ReadToEnd(); reader.Close(); responseStream.Close(); request.Abort(); response.Close(); return result.Trim(); } } catch (Exception ex) { errorMsg =string.Format("Error Message:{0},Request Url:{1},StackTrace:{2}", ex.Message ,requestUrl , ex.StackTrace); } return result; }