【知识碎片】Asp.Net 篇
51、app.config 连接字符串
<?xml version="1.0" encoding="utf-8"?>"v4.0" sku=".NETFramework,Version=v4.5" /> "dmsFolder" value="C:\local.dfs.com\Data\DMS\" /> "ConnectionString" connectionString=" Data Source=.;Initial Catalog=UserExp2;Persist Security Info=True;User ID=sa;password=mima;" providerName="System.Data.SqlClient" />
读取:
string connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString.ToString();
记得添加引用 using System.Configuration;
50、常用设计模式
savechange 设计模式:工作单元模式 :一个业务对多张表的操作,只连一次数据库,完成条记录的更新
简单工厂:返回父类或者接口的多种形态
抽象工厂:通过反射创建
单例:类似静态类 可以继承 扩展 延迟加载.....保证程序只new一次 比如队列 就可以放在单列里面
49、.net 常用 ORM框架
对象关系映射(英语:Object Relational Mapping,简称ORM,或O/RM,或O/R mapping),是一种程序技术,用于实现面向对象编程语言里不同类型系统的数据之间的转换。从效果上说,它其实是创建了一个可在编程语言里使用的“虚拟对象数据库”。
EF:Entity Framework
NHibernate
Linq
Dapper
PetaPoco
转自:http://zhan.renren.com/h5/entry/3602888498046723643
47、.net 中const 与readonly的区别???
const是静态常量,const是编译时常量;readonly是动态常量,是运行时常量,const较高效,readonly较灵活。
const和readonly都是只读的。
但是const修饰的变量必须在声明时赋值。
readonly修饰的变量可以在声明时或者构造函数里赋值。
private const double pi=3.14;
class A { private readonly int a; public A(int v) { a=v; } }
46、asp.net MVC 导出txt文件
public ActionResult ExpData() { StringBuilder sb = new StringBuilder(); string timeNow = DateTime.Now.ToString(); Response.Clear(); Response.Buffer = false; //通知浏览器 下载文件而不是打开 Response.ContentType = "application/octet-stream"; Response.AppendHeader("content-disposition", "attachment;filename=" + timeNow + ".txt;"); var operLogList = operLogBLL.LoadEntities(o=>o.IsValid==1); foreach (var item in operLogList) { sb.Append("时间:" + item.CreateTime.ToString() + "\n"); sb.Append("类别:" + item.Category.ToString() + "\n"); sb.Append("域:" + item.DomainID.ToString() + "\n"); sb.Append("用户名:" + item.AccountName.ToString() + "\n"); sb.Append("内容:" + item.Content.ToString() + "\n"); sb.Append("--------------------------------------------------\n\n"); } Response.Write(sb); Response.Flush(); Response.End(); return new EmptyResult(); }
//导出数据 function ExpData() { window.location.href = "/LogManager/ExpData"; //MySuccess("导出成功!"); };
44、动态解析二级域名
1、DomainRoute插件
2、global里URL重写
--------------------------------------------------------------------------------------------------------------------------
请求报文 接收报文
http协议 返回的请求状态码
post请求 get请求
get请求接收 context.Request.QueryString["catalog"]
post请求接收 context.Request.Form["catalog"]
Response.Redirect重定向
context.Response.Redirect("UserInfoList.ashx");
文件上传 可以用文件流的MD5 或者GUID做标识,时间不能唯一不建议
webform调用后台 变量方法
1.在前台html控件调用c#后台变量。 在后台的类代码里定义一个字符串。如 public partial class Index : System.Web.UI.Page { public string msg = ""; } 然后可以写方法改变此字符串的值。 前台调用也很简单: "Text1" type="text" value="<%=msg%>"/> 2.在前台html调用c#后台方法 后台有一个方法: public string test() { return "message"; } 前台代码: "Text2" type="text" value="<%=test()%>"/> 3.在前台js里调用c#后台变量 后台代码: public partial class Index : System.Web.UI.Page { public string msg = ""; } 前台代码: <script>alert("<%=msg%>");</script> 4.在前台js里调用c#后台变量 后台有一个方法: public string test() { return "message"; } 前台代码: <script>alert("<%=test() %>");</script> 5,前台js里调用后台带参数的方法 public string test(string a) { return a+",我是参数传进来的"; } <script>alert("<%=test("021") %>");</script> 6,前台js里调用后台带参数的方法 //商品信息 function getProInfo(t) { var result = ""; result = MallPowerSite.order.ChangeOrderEdit.GetProductInfo(t).value;//后台的方法,注意这里不用双引号 return result; }
值得注意的是,要在js中调用C#的变量和函数返回的结果,js代码必须写在页面的<script>...</script>中,而不能写在独立的*.js文件中,这样会js会将*.js的C#代码作为字符串处理,而不是变量或者方法。
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UserInfoList.aspx.cs" Inherits="CZBK.ItcastProject.WebApp._2015_5_29.UserInfoList" %> DOCTYPE html> <%@ Import Namespace="CZBK.ItcastProject.Model" %> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>title> <script type="text/javascript"> window.onload = function () { var datas = document.getElementsByClassName("deletes"); var dataLength = datas.length; for (var i = 0; i < dataLength; i++) { datas[i].onclick = function () { if (!confirm("确定要删除吗?")) { return false; } } } }; script> <link href="../Css/tableStyle.css" rel="stylesheet" /> head> <body> <form id="form1" runat="server"> <div> <a href="AddUserInfo.aspx">添加用户a> <table> <tr><th>编号th><th>用户名th><th>密码th><th>邮箱th><th>时间th><th>删除th><th>详细th><th>编辑th>tr> <%-- <%=StrHtml%>--%> <% foreach(UserInfo userInfo in UserList){%> <tr> <td><%=userInfo.Id %>td> <td><%=userInfo.UserName %>td> <td><%=userInfo.UserPass %>td> <td><%=userInfo.Email %>td> <td><%=userInfo.RegTime.ToShortDateString() %>td> <td><a href="Delete.ashx?id=<%=userInfo.Id %>" class="deletes">删除a>td> <td>详细td> <td><a href="EditUser.aspx?id=<%=userInfo.Id %>">编辑a> td> tr> <%} %> table> <hr /> div> form> body> html>
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Fdcxm_Mx.aspx.cs" Inherits="WebApplication.Fdc.Fdcxm_Mx" %> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title>title> <link href="/Css/FDC.css" type="text/css" rel="stylesheet" /> head> <body> <table border="0" cellspacing="1"> <tr> <td colspan="6" align="center" valign="middle" class="title_0"> <%=this.XmFdcInfo.XmName%> td> tr> table> <table border="0" cellspacing="1"> <tr> <td align="center" valign="middle" class="title_1"> 税款属期 td> <td align="center" valign="middle" class="title_1"> 项目固定信息数据申报表 td> <td align="center" valign="middle" class="title_1"> 项目按月信息数据申报表 td> <td align="center" valign="middle" class="title_1"> 施工企业报送数据申报表 td> tr> <tbody id="tab"> <tr> <td align="center" valign="middle"> <%=Convert.ToDateTime(this.YYS_SKSQ).ToString("yyyy-MM")%> td> <td align="center" valign="middle"> <a href="#" onclick="top.frames['MainFrame'].WinClose1('/Fdc/Jcxx.aspx?YYS_SKSQ=<%=this.YYS_SKSQ %>&XM_CODE=<%=this.XmFdcInfo.XmCode%>', '<%=this.XmFdcInfo.XmName%>房地产固定信息');"> <%if (this.GDSB_SH_JG == "审核未通过" || this.GDSB_SH_JG == "") { %>数据申报<%} %><%else { %>数据修改<%} %>a> td> <td align="center" valign="middle"> <%if (this.GDSB_SH_JG == "审核已通过") { %> <a href="#" onclick="top.frames['MainFrame'].WinClose1('/Fdc/AysbMx.aspx?YYS_SKSQ=<%=this.YYS_SKSQ %>&XM_CODE=<%=this.XmFdcInfo.XmCode%>', '<%=this.XmFdcInfo.XmName%>按月数据申报信息');"> <%if (this.AYSB_SH_JG == "审核未通过" || this.AYSB_SH_JG == "") { %>数据申报<%} %><%else { %>数据修改<%} %>a> <%} else { %>数据申报<%} %> td> <td align="center" valign="middle"> <%if (AYSB_SH_JG == "审核已通过" && this.GDSB_SH_JG == "审核已通过" && this.XmFdcInfo.XmZt != "尾盘") { %> <a href="#" onclick="top.frames['MainFrame'].WinClose1('/Fdc/SGDW.aspx?YYS_SKSQ=<%=this.YYS_SKSQ %>&XM_CODE=<%=this.XmFdcInfo.XmCode%>', '<%=this.XmFdcInfo.XmName%>报送施工企业信息');"> <%if (this.SGDW_SH_JG == "审核未通过" || this.SGDW_SH_JG == "") { %>数据申报<%} %><%else { %>数据修改<%} %>a> <%} else { %>数据申报<%} %> td> tr> <tr> <td align="center" valign="middle" class="title_1"> 历史数据 td> <td align="center" valign="middle" class="title_1"> 项目固定信息数据申报表 td> <td align="center" valign="middle" class="title_1"> 项目按月信息数据申报表 td> <td align="center" valign="middle" class="title_1"> 施工企业报送数据申报表 td> tr> <%=this.Output%> tbody> table> <script type="text/javascript" language="JavaScript"> function a() { alert("项目固定信息数据申报表,错误,请修改!"); TopView(); } function TopView(){ top.ymPrompt.close(); top.ymPrompt.win({ message: '', width: 905, height: 580, title: "项目固定信息数据申报表", iframe: false, closeBtn: true, dragOut: false }); } script> body> html>
什么时候用aspx 是时候用ashx(一般处理程序)
建议:
如果有复杂的界面布局用aspx
如果没有布局例如删除,用ashx,或者返回json数据
15、
如果往本页即post又get请求,可以在form里放一个隐藏域(input)
如果有 runat="server" 就自动添加隐藏域,判断的时候 直接判断if(isPostBack)就可以了
<body> <form id="form1" runat="server"> <div> 用户名:<input type="text" name="txtName" /><br /> 密码:<input type="password" name="txtPwd" /><br /> 邮箱:<input type="text" name="txtMail" /><br /> <%-- <input type="hidden" name="isPostBack" value="aaa" />--%> <input type="submit" value="添加用户" /> div> form> body>
16、分页
sql中的over函数和row_numbert()函数配合使用,可生成行号。可对某一列的值进行排序,对于相同值的数据行进行分组排序。
执行语句:
select row_number() over(order by AID DESC) as rowid,* from bb
dao
////// 根据指定的范围,获取指定的数据 /// /// /// /// public List GetPageList(int start,int end) { string sql = "select * from(select *,row_number()over(order by id) as num from UserInfo) as t where t.num>=@start and t.num<=@end"; SqlParameter[] pars = { new SqlParameter("@start",SqlDbType.Int), new SqlParameter("@end",SqlDbType.Int) }; pars[0].Value = start; pars[1].Value = end; DataTable da=SqlHelper.GetDataTable(sql, CommandType.Text, pars); List list = null; if (da.Rows.Count > 0) { list = new List (); UserInfo userInfo = null; foreach (DataRow row in da.Rows) { userInfo = new UserInfo(); LoadEntity(userInfo, row); list.Add(userInfo); } } return list; } /// /// 获取总的记录数 /// /// public int GetRecordCount() { string sql = "select count(*) from UserInfo"; return Convert.ToInt32(SqlHelper.ExecuteScalar(sql,CommandType.Text)); } private void LoadEntity(UserInfo userInfo, DataRow row) { userInfo.UserName = row["UserName"] != DBNull.Value ? row["UserName"].ToString() : string.Empty; userInfo.UserPass = row["UserPass"] != DBNull.Value ? row["UserPass"].ToString() : string.Empty; userInfo.Email = row["Email"] != DBNull.Value ? row["Email"].ToString() : string.Empty; userInfo.Id = Convert.ToInt32(row["ID"]); userInfo.RegTime = Convert.ToDateTime(row["RegTime"]); }
bll
////// 计算获取数据的访问,完成分页 /// /// 当前页码 /// 每页显示的记录数据 /// public List GetPageList(int pageIndex,int pageSize) { int start=(pageIndex-1)*pageSize+1; int end = pageIndex * pageSize; return UserInfoDal.GetPageList(start, end); } /// /// 获取总的页数 /// /// 每页显示的记录数 /// public int GetPageCount(int pageSize) { int recoredCount = UserInfoDal.GetRecordCount();//获取总的记录数. int pageCount =Convert.ToInt32(Math.Ceiling((double)recoredCount / pageSize)); return pageCount; }
aspx
using CZBK.ItcastProject.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace CZBK.ItcastProject.WebApp._2015_5_30 { public partial class NewList : System.Web.UI.Page { public string StrHtml { get; set; } public int PageIndex { get; set; } public int PageCount { get; set; } protected void Page_Load(object sender, EventArgs e) { int pageSize=5; int pageIndex; if(!int.TryParse(Request.QueryString["pageIndex"],out pageIndex)) { pageIndex=1; } BLL.UserInfoService UserInfoService = new BLL.UserInfoService(); int pagecount = UserInfoService.GetPageCount(pageSize);//获取总页数 PageCount = pagecount; //对当前页码值范围进行判断 pageIndex = pageIndex < 1 ? 1 : pageIndex; pageIndex = pageIndex > pagecount ? pagecount : pageIndex; PageIndex = pageIndex; Listlist= UserInfoService.GetPageList(pageIndex,pageSize);//获取分页数据 StringBuilder sb = new StringBuilder(); foreach (UserInfo userInfo in list) { sb.AppendFormat(" {0}{1} ",userInfo.RegTime.ToShortDateString(),userInfo.UserName); } StrHtml = sb.ToString(); } } }
pagebarHelper
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Common { public class PageBarHelper { public static string GetPagaBar(int pageIndex, int pageCount) { if (pageCount == 1) { return string.Empty; } int start = pageIndex - 5;//计算起始位置.要求页面上显示10个数字页码. if (start < 1) { start = 1; } int end = start + 9;//计算终止位置. if (end > pageCount) { end = pageCount; //重新计算一下Start值. start = end - 9 < 1 ? 1 : end - 9; } StringBuilder sb = new StringBuilder(); if (pageIndex > 1) { sb.AppendFormat("上一页", pageIndex - 1); } for (int i = start; i <= end; i++) { if (i == pageIndex) { sb.Append(i); } else { sb.AppendFormat("{0}",i); } } if (pageIndex < pageCount) { sb.AppendFormat("下一页", pageIndex + 1); } return sb.ToString(); } } }
<%=Common.PageBarHelper.GetPagaBar(PageIndex,PageCount)%>
17、http协议 request response server成员
http协议 超文本传输协议 包括请求响应报文 请求报文包括请求头 请求内容
request 成员
Files 接受文件 Request.Files["FileName"]
UrlReferrer 请求的来源
Url 请求的网址
UserHostAddress 访问者IP
Cookie 浏览器Cookie
MapPath 虚拟路径转物理路径 ../2016/hello.aspx -->E:\web\2016\hello.aspx
response 成员
Flush() 将缓冲区中的数据发送给用户
Clear() 清空缓冲区
ContentEncoding 输出流的编码
ContentType 输出流的内容类型 HTML(text/html) 普通文本(text/plain) jpeg (image/JPEG)
server成员
Server.Transfer("Child.aspx")
Server.Execute("Child.aspx");
这两个是一样的 都是在后台访问其他的页面 达到ifram的效果
与Response.Redirect的区别。Transfer:服务端跳转,不会向浏览器返回任何内容,所以地址栏中的URL地址不变。
Server.HtmlEncode("")
18、XSS跨站攻击
比如评论的时候,没有编码,别人写了JavaScript代码,直接可以跳转到别的网站
注释
服务器注释 不会显示到HTML <%--这是注释内容--%>
显示到HTML里
19、viewstate
当我们在写一个asp.net表单时, 一旦标明了 form runat=server ,那么,asp.net就会自动在输出时给页面添加一个隐藏域
<input type="hidden" name="__VIEWSTATE" value=""> MVC中没有 viewstate赋值using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace CZBK.ItcastProject.WebApp._2015_5_30 { public partial class ViewStateDemo : System.Web.UI.Page { public int Count { get; set; } protected void Page_Load(object sender, EventArgs e) { int count = 0; if (ViewState["count"] != null) { count = Convert.ToInt32(ViewState["count"]); count++; Count = count; } ViewState["count"] = Count;//当我们把数据给了ViewState对象以后,该对象会将数据进行编码,然后存到__VIEWSTATE隐藏域中,然后返回给浏览器。 //当用户通过浏览器单击“提交”按钮,会向服务端发送一个POST请求那么__VIEWSTATE隐藏域的值也会提交到服务端,那么服务端自动接收__VIEWSTATE隐藏域的值,并且再反编码,重新赋值给ViewState对象。 } } }
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ViewStateDemo.aspx.cs" Inherits="CZBK.ItcastProject.WebApp._2015_5_30.ViewStateDemo" %> DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>title> head> <body> <form id="form1" runat="server"> <div> <span><%=Count%>span> <input type="submit" value="计算" /> div> form> body> html>
20、cookie
存在浏览器中 指定时间:存在硬盘中,关闭浏览器也会存在,不指定时间存在浏览器内存中,关闭就没了
21、session
浏览器关闭就不见了 因为ID是一cookie的形式存在浏览器之前传送,没有指定过期时间,存在浏览器内存中
22、page_init()
和page_Load()一样都是自动执行,不过这个在page_Load之前执行
统一的验证:写一个pagebase继承system.web.UI.page 然后在Page_Init()方法里写验证
23、自动登录实现原理
如果勾选了自动登录,把用户名和密码存在cookie中 记得加密,下次登录的时候直接进入get请求,给session赋值
http://www.liaoxuefeng.com/article/00146129217054923f7784c57134669986a8875c10e135e000using CZBK.ItcastProject.Model; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace CZBK.ItcastProject.WebApp._2015_5_31 { public partial class UserLogin : System.Web.UI.Page { public string Msg { get; set; } public string UserName { get; set; } protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) { //string userName = Request.Form["txtName"]; //UserName = userName; if (CheckValidateCode())//先判断验证码是否正确. { CheckUserInfo(); } else { //验证码错误 Msg = "验证码错误!!"; } } else { //判断Cookie中的值。自动登录 CheckCookieInfo(); } } #region 判断用户名密码是否正确 protected void CheckUserInfo() { //获取用户输入的用户名和密码. string userName = Request.Form["txtName"]; UserName = userName; string userPwd = Request.Form["txtPwd"]; //校验用户名密码. BLL.UserInfoService UserInfoService = new BLL.UserInfoService(); string msg = string.Empty; UserInfo userInfo = null; //判断用户名与密码 if (UserInfoService.ValidateUserInfo(userName, userPwd, out msg, out userInfo)) { //判断用户是否选择了“自动登录” if (!string.IsNullOrEmpty(Request.Form["autoLogin"]))//页面上如果有多个复选框时,只能将选中复选框的的值提交到服务端。 { HttpCookie cookie1 = new HttpCookie("cp1",userName); HttpCookie cookie2 = new HttpCookie("cp2", Common.WebCommon.GetMd5String(Common.WebCommon.GetMd5String(userPwd))); cookie1.Expires = DateTime.Now.AddDays(7); cookie2.Expires = DateTime.Now.AddDays(7); Response.Cookies.Add(cookie1); Response.Cookies.Add(cookie2); } Session["userInfo"] = userInfo; Response.Redirect("UserInfoList.aspx"); } else { Msg = msg; } } #endregion #region 校验Cookie信息. protected void CheckCookieInfo() { if (Request.Cookies["cp1"] != null && Request.Cookies["cp2"] != null) { string userName = Request.Cookies["cp1"].Value; string userPwd = Request.Cookies["cp2"].Value; //校验 BLL.UserInfoService UserInfoService = new BLL.UserInfoService(); UserInfo userInfo=UserInfoService.GetUserInfo(userName); if (userInfo != null) { //注意:在添加用户或注册用户时一定要将用户输入的密码加密以后在存储到数据库中。 if (userPwd == Common.WebCommon.GetMd5String(Common.WebCommon.GetMd5String(userInfo.UserPass))) { Session["userInfo"] = userInfo; Response.Redirect("UserInfoList.aspx"); } } Response.Cookies["cp1"].Expires = DateTime.Now.AddDays(-1); Response.Cookies["cp2"].Expires = DateTime.Now.AddDays(-1); } } #endregion #region 判断验证码是否正确 protected bool CheckValidateCode() { bool isSucess = false; if (Session["validateCode"] != null)//在使用Session时一定要校验是否为空 { string txtCode = Request.Form["txtCode"];//获取用户输入的验证码。 string sysCode = Session["validateCode"].ToString(); if (sysCode.Equals(txtCode, StringComparison.InvariantCultureIgnoreCase)) { isSucess = true; Session["validateCode"] = null; } } return isSucess; } #endregion } }
24、request[""] 自动识别post get
POST GET:context.request["name"] post:context.request.form["name"] get:context.request.Querystring["name"]
25、手写异步请求
<script type="text/javascript"> $(function () { $("#btnGetDate").click(function () { //开始通过AJAX向服务器发送请求. var xhr; if (XMLHttpRequest) {//表示用户使用的高版本IE,谷歌,狐火等浏览器 xhr = new XMLHttpRequest(); } else {// 低IE xhr=new ActiveXObject("Microsoft.XMLHTTP"); } xhr.open("get", "GetDate.ashx?name=zhangsan&age=12", true); xhr.send();//开始发送 //回调函数:当服务器将数据返回给浏览器后,自动调用该方法。 xhr.onreadystatechange = function () { if (xhr.readyState == 4) {//表示服务端已经将数据完整返回,并且浏览器全部接受完毕。 if (xhr.status == 200) {//判断响应状态码是否为200. alert(xhr.responseText); } } } }); }); </script>
<script src="../Js/jquery-1.7.1.js"></script> <script type="text/javascript"> $(function () { $("#btnPost").click(function () { var xhr; if (XMLHttpRequest) { xhr = new XMLHttpRequest(); } else { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } xhr.open("post", "GetDate.ashx", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.send("name=zhangsan&pwd=123"); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { if (xhr.status == 200) { alert(xhr.responseText); } } } }); }); </script>
var xhr= new XMLHttpRequest(); xhr.open("get", "GetDate.ashx?name=zhangsan&age=12", true); xhr.send(); xhr.onreadystatechange = function () { if (xhr.readyState == 4) {//表示服务端已经将数据完整返回,并且浏览器全部接受完毕。 if (xhr.status == 200) {//判断响应状态码是否为200. alert(xhr.responseText); } } }
26、统一布局
webform:ifram 母版页 (或者用第三方框架如fineUI) VTemplate模板 MVC:razor视图
27、缓存cache
和session的区别
每个用户都有自己单独的session
但是cache的数据是大家共享的
相同:都放在服务器内存中
using CZBK.ItcastProject.Model; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Caching; using System.Web.UI; using System.Web.UI.WebControls; namespace CZBK.ItcastProject.WebApp._2015_6_6 { public partial class CacheDemo : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //判断缓存中是否有数据. if (Cache["userInfoList"] == null) { BLL.UserInfoService UserInfoService = new BLL.UserInfoService(); Listlist = UserInfoService.GetList(); //将数据放到缓存中。 // Cache["userInfoList"] = list; //第二种赋值方式 Cache.Insert("userInfoList", list); //赋值的重载方法 可以指定缓存时间 //不推荐用这么多参数的重载,这里只是介绍一下,缓存依赖性什么的完全没必要,在数据库插入的时候做一下操作就可以了 Cache.Insert("userInfoList", list, null, DateTime.Now.AddSeconds(5), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, RemoveCache); Response.Write("数据来自数据库"); //Cache.Remove("userInfoList");//移除缓存 } else { List list = (List )Cache["userInfoList"]; Response.Write("数据来自缓存"); } } protected void RemoveCache(string key, object value, CacheItemRemovedReason reason) { if (reason == CacheItemRemovedReason.Expired) { //缓存移除的原因写到日志中。 } } } }
文件缓存依赖项
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Web.Caching; using System.Web.UI; using System.Web.UI.WebControls; namespace CZBK.ItcastProject.WebApp._2015_6_6 { public partial class FileCacheDep : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string filePath = Request.MapPath("File.txt"); if (Cache["fileContent"] == null) { //文件缓存依赖. CacheDependency cDep = new CacheDependency(filePath); string fileContent = File.ReadAllText(filePath); Cache.Insert("fileContent", fileContent, cDep); Response.Write("数据来自文件"); } else { Response.Write("数据来自缓存:"+Cache["fileContent"].ToString()); } } } }
28、页面缓存
webform
在页面加<%@ OutputCache Duration="5" VaryByParam="*"%> 就可以了,如果有参数VaryByParam="id" 两个参数VaryByParam="id;type" 所有参数VaryByParam="*"
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ShOWDetail.aspx.cs" Inherits="CZBK.ItcastProject.WebApp._2015_6_6.ShOWDetail" %> <%@ OutputCache Duration="5" VaryByParam="*"%> DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>title> head> <body> <form id="form1" runat="server"> <div> <asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="125px">asp:DetailsView> div> form> body> html>
MVC
在MVC中要如果要启用页面缓存,在页面对应的Action前面加上一个OutputCache属性即可。
[HandleError] public class HomeController : Controller { [OutputCache(Duration = 5, VaryByParam = "none")] public ActionResult Index() { return View(); } }
http://www.cnblogs.com/iamlilinfeng/p/4419362.html#t5
29、session分布式存储方案
其他机器:session状态服务器,单独一台机器,专门记录所有机器的session状态
数据库
上面两个性能太低,微软给的解决方案,不推荐用。建议用memcache,redis
30、错误页面配置
mode 值
On 指定启用自定义错误。如果没有指定 defaultRedirect,用户将看到一般性错误。
Off 指定禁用自定义错误。这允许显示详细的错误。
RemoteOnly 指定仅向远程客户端端显示自定义错误,并向本地主机显示 ASP.NET 错误。这是默认值。
<configuration> <system.web> <customErrors mode="On" defaultRedirect="MyErrorPage.html"> <error statusCode="403" redirect="NoAccess.htm" /> <error statusCode="404" redirect="FileNotFound.html" /> customErrors> system.web> configuration>
ps:iis中有一错误页面 选项 也需要配置一下
32、HttpModule
创建httpapplacation之后 会遍历所有的httpmodule 包括web.config中配置的
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; namespace CZBK.ItcastProject.Common { //过滤器。 public class CheckSessionModule:IHttpModule { public void Dispose() { throw new NotImplementedException(); } public void Init(HttpApplication context) { //URL重写。 // context.AcquireRequestState+=context_AcquireRequestState; } public void context_AcquireRequestState(object sender, EventArgs e) { //判断Session是否有值. HttpApplication application = (HttpApplication)sender; HttpContext context = application.Context; string url = context.Request.Url.ToString();//获取用户请求的URL地址. if (url.Contains("AdminManger"))//网站程序所有的后台页面都放在该文件夹中。 { if (context.Session["userInfo"] == null) { context.Response.Redirect("/2015-02-27/Login.aspx"); } } } } }
33、Global
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Security; using System.Web.SessionState; namespace CZBK.ItcastProject.WebApp { public class Global : System.Web.HttpApplication { ////// 整个WEB应用程序的入口。相当于Main函数.该方法只执行一次,当WEB应用程序第一次启动时,执行该方法,后续请求其它页面该方法不在执行。该方法中一般完成对整个网站的初始化。 /// /// /// protected void Application_Start(object sender, EventArgs e) { //这个只执行一次,其他的是用户请求一次执行一次,这个和用户请求无关,只有服务器上网站启动的时候,初始化启动 } /// /// 开启会话的时候执行该方法。 /// /// /// protected void Session_Start(object sender, EventArgs e) { //统计访问人数. //访问人数+1. //Application:服务端状态保持机制,并且放在该对象中的数据大家共享的。使用该对象时必须加锁。 Application.Lock(); if (Application["count"] != null) { int count = Convert.ToInt32(Application["count"]); count++; Application["count"] = count; //向永久保存访客人数必须将该数据存储到文件或数据库中。 } else { Application["count"] = 1; } Application.UnLock(); } protected void Application_BeginRequest(object sender, EventArgs e) { } protected void Application_AuthenticateRequest(object sender, EventArgs e) { } /// /// 注意的方法。该方法会捕获程序中(所有)没有处理的异常。并且将捕获的异常信息写到日志中。 /// /// /// protected void Application_Error(object sender, EventArgs e) { HttpContext.Current.Server.GetLastError();//捕获异常信息. //将捕获的异常信息写到日志中。 } /// /// 会话结束的时候执行该方法。 /// /// /// protected void Session_End(object sender, EventArgs e) { //不是实时的,和session的默认有效期是20分钟有关 } /// /// 整个应用程序结束的时候执行。 /// /// /// protected void Application_End(object sender, EventArgs e) { } } }
34、进程
//获取所有的进程的信息 //Process[] ps=Process.GetProcesses(); //foreach (Process p in ps) //{ // //p.Kill(); // Console.WriteLine(p.ProcessName); //} //获取当前进程 //Process p= Process.GetCurrentProcess();//获取当前的进程 //Console.WriteLine(p.ProcessName); //启动别的进程 //Process.Start("notepad.exe"); //flv. ffmpeg.exe//很好的视频转换工具 //视频转码解决方案,用户传到服务器,通过进行启动第三方软件(如:ffmpeg.exe)进行转换
35、线程
////// 将计算的任务交给另外一个线程来执行,UI线程还是负责与用户进行打交道。默认情况线程所执行的任务完成了,该线程也就终止了。 /// /// /// //bool isStop = true;//推荐使用这种方式结束线程,不是thread.Abort() private void button2_Click(object sender, EventArgs e) { ThreadStart threadStart=new ThreadStart(StartCacul); Thread thread = new Thread(threadStart); // thread.Priority = ThreadPriority.Normal;//建议. // thread.Name = "shit"; //thread.Abort();//强制终止线程。尽量不要该方法 // thread.Join(1000);//主线程会阻塞(睡眠、等待1000毫秒)等待 thread.Start();//将该线程标记可运行状态。 } private void StartCacul() { // while (isStop)//推荐使用这种方式结束线程,不是thread.Abort() //{ int a = 0; for (int i = 0; i < 999999999; i++) { a = i; } // MessageBox.Show(a.ToString()); this.txtNum.Text = a.ToString(); //} }
////// 后台线程:当窗体关闭该线程也就结束了。 /// /// /// private void button3_Click(object sender, EventArgs e) { Thread thread1 = new Thread(StartCacul); thread1.IsBackground = true;//这个值表示窗体关闭,线程就关闭 thread1.Start(); }
线程池:
using System; using System.Threading; namespace ThreadDemo { class program { static void Main() { int nWorkThreads; int nCompletionPortThreads; ThreadPool.GetMaxThreads(out nWorkThreads, out nCompletionPortThreads); Console.WriteLine("Max worker threads: {0}, I/O completion threads: {1}",nWorkThreads, nCompletionProtThreads); for(int i = 0; i < 5; i++) { ThreadPool.QueueUserWorkItem(JobForAThread); } Thread.Sleep(3000); } static void JobForAThread(object state) { for(int i = 0; i < 3; i++) { Console.WriteLine("loop {0}, running inside pooled thread {1}", i, Thread.CurrentThread.ManagedThreadId); Thread.Sleep(50); } } } }
36、redis队列
大致应该是两个redis的方法
EnqueueItemOnList 将一个元素存入指定ListId的List
DequeueItemFromList 将指定ListId的List
应用:
public class MyExceptionFilterAttribute : HandleErrorAttribute { //版本2:使用Redis的客户端管理器(对象池) public static IRedisClientsManager redisClientManager = new PooledRedisClientManager(new string[] { //如果是Redis集群则配置多个{IP地址:端口号}即可 //例如: "10.0.0.1:6379","10.0.0.2:6379","10.0.0.3:6379" "127.0.0.1:6379" }); //从池中获取Redis客户端实例 public static IRedisClient redisClient = redisClientManager.GetClient(); public override void OnException(ExceptionContext filterContext) { //将异常信息入队 redisClient.EnqueueItemOnList("ExceptionLog", filterContext.Exception.ToString()); //跳转到自定义错误页 filterContext.HttpContext.Response.Redirect("~/Common/CommonError.html"); base.OnException(filterContext); } }
http://www.cnblogs.com/edisonchou/p/3825682.html
ps:log4net 早期版本不支持多线程 log4net 1.2.11版本以上支持
37、application19事件
38、lenght
循环的时候 尽量放在外面 否者每次循环都计算一次 不能for(int i=0,i indexOf Contains web.config C#读取 C#设置39、反编译软件 reflector IL Spy
40、判断字符串中是否存在某段字符
41、去掉最后一个逗号
RegionsStr = RegionsStr.Remove(RegionsStr.LastIndexOf(","), 1); //去掉最后一个逗号
42、读取xml
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Xml;
using WebCenter.Model;
namespace WebCenter.Service
{
///
<?xml version="1.0" encoding="utf-8" ?>
<CityIpConfig>
<ProvinceIp ProvinceName="北京">
<CityIp CityName="北京" SkipCity="北京" CityCode="" CityValue="" CitySkipUrl="http://webbj.imtfc.com/Index.html" >CityIp>
ProvinceIp>
<ProvinceIp ProvinceName="福建">
<CityIp CityName="厦门" SkipCity="厦门" CityCode="XM" CityValue="4" CitySkipUrl="http://webcenter.imtfc.com/WebConstruction.html" >"CityIp>
<CityIp CityName="福州" SkipCity="福州" CityCode="FZ" CityValue="3" CitySkipUrl="http://webcenter.imtfc.com/WebConstruction.html" >CityIp>
<CityIp CityName="龙岩" SkipCity="厦门" CityCode="XM" CityValue="4" CitySkipUrl="http://webcenter.imtfc.com/WebConstruction.html" >CityIp>
<CityIp CityName="泉州" SkipCity="厦门" CityCode="XM" CityValue="4" CitySkipUrl="http://webcenter.imtfc.com/WebConstruction.html" >CityIp>
<CityIp CityName="其他" SkipCity="福州" CityCode="FZ" CityValue="3" CitySkipUrl="http://webcenter.imtfc.com/WebConstruction.html" >CityIp>
ProvinceIp>
<ProvinceIp ProvinceName="其他" SkipDafualt="北京" CitySkipUrl="http://webbj.imtfc.com/Index.html">
ProvinceIp>
CityIpConfig>
43、list取随机
Random rd = new Random();
List<string> liststr = new List<string>();
liststr.Add("aaa");
liststr.Add("bbb");
liststr.Add("ccc");
liststr.Add("111");
liststr.Add("222");
liststr.Add("333");
//随机一个
var s = liststr.OrderBy(_ => Guid.NewGuid()).First();
//随机两个
var ss = liststr.OrderBy(_ => Guid.NewGuid()).Take(2);
//乱序
var sss = liststr.OrderBy(o => rd.Next(0, liststr.Count())).ToList();
2、C#读取web.config文件信息
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="name" value="name1"/>
appSettings>
configuration>
string name = System.Web.Configuration.WebConfigurationManager.AppSettings["name"];
System.Configuration.ConfigurationManager.AppSettings["SqlConnectionStr"]; System.Web.Configuration.WebConfigurationManager.AppSettings.Set("name", "name2");