关于.net的一些记录
.net在线代码测试网站:
https://try.dot.net/
1、HttpWebRequest调用接口
string strResult = ""; try { HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://testapi.wzeye.cn/connect/token"); myRequest.Method = "POST"; myRequest.ContentType = "application/x-www-form-urlencoded"; string paraUrlCoded = System.Web.HttpUtility.UrlEncode("scope"); paraUrlCoded += "=" + System.Web.HttpUtility.UrlEncode(tokenscope); paraUrlCoded += "&" + System.Web.HttpUtility.UrlEncode("grant_type"); paraUrlCoded += "=" + System.Web.HttpUtility.UrlEncode(tokengranttype); paraUrlCoded += "&" + System.Web.HttpUtility.UrlEncode("client_id"); paraUrlCoded += "=" + System.Web.HttpUtility.UrlEncode(tokenclientid); paraUrlCoded += "&" + System.Web.HttpUtility.UrlEncode("client_secret"); paraUrlCoded += "=" + System.Web.HttpUtility.UrlEncode(tokenclientsecret); try { byte[] payload; //将URL编码后的字符串转化为字节 payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded); //设置请求的 ContentLength myRequest.ContentLength = payload.Length; // 获得请 求流 Stream writer = myRequest.GetRequestStream(); //将请求参数写入流 writer.Write(payload, 0, payload.Length); // 关闭请求流 writer.Close(); System.Net.HttpWebResponse response; // 获得响应流 response = (System.Net.HttpWebResponse)myRequest.GetResponse(); System.IO.Stream myStream; myStream = response.GetResponseStream(); //HttpWebResponse HttpWResp = (HttpWebResponse)myRequest.GetResponse(); //Stream myStream = HttpWResp.GetResponseStream(); StreamReader sr = new StreamReader(myStream, Encoding.UTF8); StringBuilder strBuilder = new StringBuilder(); while (-1 != sr.Peek()) { strBuilder.Append(sr.ReadLine()); } strResult = strBuilder.ToString(); } catch (Exception exp) { strResult = "错误:" + exp.Message; } } catch (Exception exp) { strResult = "错误:" + exp.Message; } return strResult;
2、
取得控制台应用程序的根目录方法
1:Environment.CurrentDirectory 取得或设置当前工作目录的完整限定路径
2:AppDomain.CurrentDomain.BaseDirectory 获取基目录,它由程序集冲突解决程序用来探测程序集
取得WinForm应用程序的根目录方法
1:Environment.CurrentDirectory.ToString();//获取或设置当前工作目录的完全限定路径
2:Application.StartupPath.ToString();//获取启动了应用程序的可执行文件的路径,不包括可执行文件的名称
3:Directory.GetCurrentDirectory();//获取应用程序的当前工作目录
4:AppDomain.CurrentDomain.BaseDirectory;//获取基目录,它由程序集冲突解决程序用来探测程序集
5:AppDomain.CurrentDomain.SetupInformation.ApplicationBase;//获取或设置包含该应用程序的目录的名称
取得web应用程序的根目录方法
1.HttpContext.Current.Server.MapPath("~/configs/ChannelUsers.xml")
HttpContext.Current返回当前请求的 HttpContext 对象。如此我们就可以直接访问Request、Response、Session、Application等对象,和Page中访问等同。
获取网站根目录的方法有几种如:
Server.MapPath(Request.ServerVariables["PATH_INFO"])
Server.MapPath("/")
Server.MapPath("")
Server.MapPath(".")
Server.MapPath("../")
Server.MapPath("..")
Page.Request.ApplicationPath
以上的方法可以在.aspx中访问,但是如果你在winform文件就不能用。
HttpContext.Current.Server.MapPath();
System.Web.HttpContext.Current.Request.PhysicalApplicationPath在.cs文件中可以用。
但是HttpContext.Current.Server.MapPath();这个获取的是文件的路径而不是根目录。
只有System.Web.HttpContext.Current.Request.PhysicalApplicationPath 这个才是获取的根目录,在写获取数据库路径是应该用这个。
3、获得当前url
.net
string anjianurl = $"{Request.Url.Scheme}://{Request.Url.Authority}/Forms/HongYang/AnJianWeiHu.aspx?id={e.GetDataValue("ID")}&rid=1071&isapproval=true&dsd={DateTime.Now.Ticks}";
4、int、datetime转换
if(int.TryParse(no,out var iStage)) { } if(DateTime.TryParse(now,out var iStage)) { }
System.Func<string, bool> getShowTask = (ID) => { using (var task = new TaskDataContext()) { return (from b in task.Task_JiHua where b.ProjectID == ID && b.IsProject == true && (b.JiHuaZTText == "待执行" || b.JiHuaZTText == "执行中" || b.JiHuaZTText == "已延期" || b.JiHuaZTText == "已完成") select new { b.ID }).ToList().Count() > 0; } };
5、存储临时数据
TempData["is_face"] = 1;
注意:TempData的生命周期只有一次调用,如果需要持久化,请加keep
TempData["is_face"] = 1; TempData.Keep(); int.TryParse(TempData["is_face"].ToString(), out is_face); TempData.Keep("is_face");
6、string 转 Enum
var t = (WaypointType)Enum.Parse(typeof(WaypointType), pointType);
7、Enum转list
public static string GetWaiPointType(WaypointType waypointType) { return waypointType switch { WaypointType.HoldEnd => "", _ => waypointType.ToString(), }; } public class EnumModel { public string pointType { get; set; } public string Description { get; set; } } public static List<EnumModel> ConvertEnumToList() { List<EnumModel> list = new List<EnumModel>(); foreach (var e in Enum.GetValues(typeof(WaypointType))) { EnumModel m = new EnumModel(); m.pointType = e.ToString(); m.Description = GetWaiPointType((WaypointType)e); if (!string.IsNullOrWhiteSpace(m.Description)) { list.Add(m); } } return list; }