Common. NET Function Code Summary (2). net Function Code Summary
Common. NET Function Code Summary
23. Obtain and set the Hierarchical Cache
Get cache: first obtain from the local cache. If not, read the distributed cache.
Write cache: write local cache and distributed cache at the same time
Private static T GetGradeCache <T> (string key) where T: struct {MemoryCacheManager localCache = MemoryCacheManager. Instance; if (! LocalCache. IsSet (key) {// The cache T remoteValue = MemCacheManager. Instance. Get <T> (key); if (! ValueType. equals (remoteValue, default (T) {// If localCache is available remotely. 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 );}
24. Find the absolute path of the relative directory
Sometimes, we need to specify a relative directory relative to the current root directory. For example, to store log files outside the site directory, we can use the./logs/method:
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);
This code will create a log file named by date on behalf of the machine in the log directory outside the site directory.
25. multiple attempts to write log files
The log file may be concurrently written, and the system may prompt "the file is occupied by another process". Therefore, you can try to write the file multiple times. The following method recursively attempts to write files. If the number of attempts is used up, an error is returned.
/// <Summary> // Save the log file /// </summary> /// <param name = "logFileName"> file name without extension </param> // /<param name = "logText"> log content </param> // <param name = "tryCount"> if the number of failed attempts, it is recommended that the value be no greater than 100. If the value is 0, do not try </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 ("yyy YMMdd "); 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 Excep Tion ("Save log file Error, try count more times! ");}}}
26. ASP. NET obtains the IP address of the client.
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;
27. ASP. net mvc obtains the requested URL in the Action.
There are three methods,
1) ASP. net mvc obtains the path to request other actions in the default Action of the controller.
For example, obtain the path in the default Index Action, as follows:
string sso_url= "http://" + Request.Url.Authority + Request.Url.AbsolutePath + "/SSO?id=" + userid;
2) obtain the path of the current controller from other actions.
string ctrName = RouteData.Values["controller"].ToString(); string redirectUrl = "http://" + Request.Url.Authority + "/" + ctrName + "/SSO?id=" + userid;
3) directly obtain the path of the current Action request
string url=Request.Url.ToString();
28. ASP. net mvc Action returns plain text information that can be directly viewed in the browser
You must specify the contentType of Context as "text/plain". The Code is as follows:
Public ActionResult SendMessage () {string txt = "Hello! "; Return Content (text," text/plain ", System. Text. Encoding. UTF8 );}
29. Use Linq2XML to read and write XML
Here we mainly use XDocument and XElement objects to operate XML content. The Code is as follows:
Public static class XDocumentExtentsion {// generate the declaration part of the 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 XElem Ent ("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 nod E, 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 ;}
30. Custom Code for accessing Web Content
Use the HttpWebRequest and HttpWebResponse objects to complete Web access. For. NET 4.5, we recommend that you directly use the HttpClient object:
/// <Summary> /// obtain the request result /// </summary> /// <param name = "requestUrl"> request address </param> /// <param name = "timeout"> timeout (seconds) </param> /// <param name = "requestXML"> request xml content </param> /// <param name = "isPost"> whether to submit a post request </param> /// <param name = "encoding"> the encoding format is as follows: UTF-8 </param> /// <param name = "errorMsg"> thrown error message </param> /// <returns> return request result </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 = r Esponse. 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 ;}