Asp.Net six built-in objects

When the previous study mvc pipeline processing model, we know that throughout the HttpContext of an object, resulting in HttpRuntime, now we call Asp.Net six built-in objects, in fact, HttpContext properties. Specifically:

A: Request Http request various information that is provided

A: Heads Request information inside by the code:

 1 public ActionResult Request()
 2 {
 3     List<string> requestHeads = new List<string>();
 4     foreach (var item in base.Request.Headers.AllKeys)
 5     {
 6         requestHeads.Add($"{item}:{base.Request.Headers[item]}");
 7     }
 8     ViewData["requestHead"] = requestHeads;
 9     return View();
10 }

views:

 1 @{
 2     Layout = null;
 3 }
 4 <html>
 5 <head>
 6     <meta name="viewport" content="width=device-width" />
 7     <title>Request</title>
 8 </head>
 9 <body>
10     <div> 
11         RequestHeads:<br />
12         @{ 
13             foreach (var item in (List<string>)ViewData["requestHead"])
14             {
15                 <label>@item</label><br />
16             } 
17         }
18         <div>
19         </div>
20     </div>
21 </body>
22 </html>
View Code

Pages following results were obtained, that is, inside RequestHeads complete information can be acquired, by background code: context.Request.Headers [ "key name"], which may further comprise a custom key, such as of BasicAuth; in fact, the request asp.net_isapi interpret the information is parsed out in accordance with the http protocol.

B: In addition, also acquired URL, Form, Params and many other information, as long as the HTTP request can get over the basic, specific reference parameter form property url parameter url address HttpRequestBase class urlreferer content-encoding, http requests various information is provided, which is the background can get context.Request.Headers [ "User-Agent"]; includes custom --BasicAuth; interpretation information is requested in accordance with the http protocol analysis asp.net_isapi from

 

Two: Response that is a response

mvc ultimately render output using Response.Write methods, conclude various extensions result is then serialized by the response output to the client in response to the content, in addition to the contents of the response body (json / html / file), in fact there are many things, a variety of header, etc., then these things out in response to the browser to use. Before we have done compression, caching, cookie, etc. are written in the Response. Then the browser will do the appropriate settings based on these settings. Specifically how to set Response respond to things, we come and collect with compression cache to give an example. code show as below:

compression:

. 1   ///  <Summary> 
2   /// browser requests --- --- represents support for the default format is not compressed IIS
 3   /// when --- --- detected in response to a format supported by the data compression (IIS server) --- response in advance plus-Encoding Content
 4   /// --- browser to view the data in a compressed format decompression format --- - (no matter what you are, you can compress decompress)
 5   / //  
6   /// compression is decompression browser IIS
 7   /// like lucene word, the repeating unit may save space
 . 8   ///  </ Summary> 
. 9   public  class CompressActionFilterAttribute: the ActionFilterAttribute
 10  {
 . 11       public  the override  void the OnActionExecuting ( filterContext ActionExecutingContext)
 12 is       {
13          var request = filterContext.HttpContext.Request;
14          var respose = filterContext.HttpContext.Response;
15          string acceptEncoding = request.Headers["Accept-Encoding"];//检测支持格式
16          if (!string.IsNullOrWhiteSpace(acceptEncoding) && acceptEncoding.ToUpper().Contains("GZIP"))
17          {
18              respose.AddHeader("Content-Encoding", "gzip");//Specify the type of response header 
. 19               respose.Filter = new new GZipStream (respose.Filter, CompressionMode.Compress); // compression type designated 
20           }
 21       }
 22   }
View Code

Cache:

 1 public class CacheFilterAttribute : ActionFilterAttribute
 2     {
 3         /// <summary>
 4         /// 缓存时长 单位s
 5         /// </summary>
 6         private int _MaxSecond = 0;
 7         public CacheFilterAttribute(int duration)
 8         {
 9             this._MaxSecond = duration;
10         }
11         public CacheFilterAttribute()
12         {
13            this._MaxSecond = 60;
14         }
15         /// <summary>
16         /// action执行后
17         /// </summary>
18         /// <param name="filterContext"></param>
19         public override void OnActionExecuted(ActionExecutedContext filterContext)
20         {
21             if (this._MaxSecond <= 0) return;
22 
23             HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;
24             TimeSpan cacheDuration = TimeSpan.FromSeconds(this._MaxSecond);
25 
26             cache.SetCacheability(HttpCacheability.Public);
27             //cache.SetLastModified(DateTime.Now.AddHours(8).Add(cacheDuration));
28             //cache.SetExpires(DateTime.Now.AddHours(8).Add(cacheDuration));//GMT时间 格林威治时间 
29             cache.SetExpires(DateTime.Now.Add(cacheDuration));
30             cache.SetMaxAge(cacheDuration);
31             cache.AppendCacheExtension("must-revalidate, proxy-revalidate");
32         }
33     }
View Code

Response browser that is obtained can be set following:

 

Three: Application of something that is global, shared by multiple users

We know to deploy IIS above project is more complicated, that each user has access to their own domains, which are not shared, each running their own domain resolution, but the Application is to provide a global variable that is not will Fenwick, one Application is used by each visitor. Because it involves is global, so this variable is rarely used to. But can this variable statistics about the traffic. But every time you need to unlock the lock use, or high concurrency will be affected. Here also tell us about some of the media to use variables:

 1 #region Application
 2 context.Application.Lock();//ASP.NET 应用程序内的多个会话和请求之间共享信息
 3 context.Application.Lock();
 4 context.Application.Add("try", "die");
 5 context.Application.UnLock();
 6 object aValue = context.Application.Get("try");
 7 aValue = context.Application["try"];
 8 context.Application.Remove("命名对象");
 9 context.Application.RemoveAt(0);
10 context.Application.RemoveAll();
11 context.Application.Clear();
12 
13 context.Items["123"] = "123";//单一会话,不同环境都可以用,比如在httpmodule获取到的信息,想传递给action;随着context释放
14 #endregion
View Code

 

四:Server也就是个帮助类库,具体详情参考HttpServerUtilityBase,下面仅仅列取一些常用的方法:

1 #region Server
2 //辅助类 Server
3 string encode = context.Server.HtmlEncode("<我爱我家>"); //HtmlEnode编码
4 string decode = context.Server.HtmlDecode(encode);//HtmlEnode解码
5 
6 string physicalPath = context.Server.MapPath("/Home/Index");//只能做物理文件的映射
7 string encodeUrl = context.Server.UrlEncode("<我爱我家>"); //URLencode编码
8 string decodeUrl = context.Server.UrlDecode(encodeUrl);  //URLencode解码
9 #endregion

 

五: Session即是用户第一次产生,一个用户一个Session;是字典式存储的;session保存的是sessionid和value,value是个集合,集合有个currentUser的key,即是一次SessionId可以对应多个key,一个key对应一个Value的值。

1:Session的一般用法:A:用户登录验证,登录时写入,验证时获取; B:验证码;C:跳转当前页;

2:Session的代码操作如下:

 1  #region Session 的存储,可以存储各种各样的值,然后以键值对的形式存储
 2  var currentUser = new CurrentUser()
 3  {
 4      Id = 1,
 5      Name = "wss",
 6      Remark = "test by wss "
 7  };
 8  var context = base.HttpContext;
 9  var sessionUser = context.Session["CurrentUser"];
10  context.Session["CurrentUser"] = currentUser;
11  context.Session["CurrentUser1"] = "wss";
12  context.Session["CurrentUser2"] = 111;
13  context.Session["CurrentUser3"] = DateTime.Now;
14  context.Session.Timeout = 3;//minute  session过期等于Abandon,过期日期是滑动时间,即是每次访问都会在当前访问的时间上面增加3分钟
15  #endregion
16 
17  #region Session的取值,直接使用键即可,取出来的是object类型
18  var CurrentUser = context.Session["CurrentUser"];
19  var CurrentUser1 = context.Session["CurrentUser1"];
20  var CurrentUser2 = context.Session["CurrentUser2"];
21  var CurrentUser3 = context.Session["CurrentUser3"];
22  #endregion
23 
24  #region Session的清除方式
25  context.Session["CurrentUser"] = null;//表示将指定的键的值清空,并释放掉,但是session的key还是存在的
26  context.Session.Remove("CurrentUser"); //将session中的key跟value移除掉
27  context.Session.Clear();//表示将会话中所有的session的键值都清空,但是session还是依然存在,
28  context.Session.RemoveAll();//表示将会话中所有的session的键值都清空
29  context.Session.Abandon();//就是把当前Session对象删除了,下一次就是新的Session了 ,介个使用同一个浏览器测试没有出现想要的效果  
30  #endregion:

3:Session的特点:

A:是服务器内存(sessionstateserver/SQLServer),所以体积不要太大,可以存敏感信息,但是重启丢失。

B:因为一个用户针对于一条session,而且session是存储在内存中,那如果负载均衡下面的session如果共享呢,可以通过会话粘滞/session存储在固定的服务中来解决介个问题

C:mvc中的Tempdate是使用Session来传值的。

 

 六:Cookie是存储在客户端(浏览器)上面的一连串字符串,一个用户一个Cookie,字典式存储;

1:Cookie的使用方向:A:用户登录验证,登录时写入,验证时获取;B: ValidateAntiForgeryToken;C:保存用户数据(记住账号;购物车;访问过那几个页面;);

2:cookie的代码使用:

 1 var context = base.HttpContext;
 2 var currentUser = new CurrentUser()
 3 {
 4     Id = 1,
 5     Name = "wss",
 6     Remark = "test by wss Cookie"
 7 };
 8 #region cookie的存储
 9 
10 HttpCookie myCookie = new HttpCookie("CurrentUser");
11 myCookie.Value = JsonHelper.ObjectToString<CurrentUser>(currentUser); //只能是字符串
12 myCookie.Expires = DateTime.Now.AddMinutes(5);//如果设置Expires,则会保存到硬盘,不设置就是内存cookie--关闭浏览器就丢失
13 context.Response.Cookies.Add(myCookie);//一定要输出
14 
15 #endregion
16 
17 #region cookie的取值
18 HttpCookie myCookie1 = context.Request.Cookies["CurrentUser"];
19 #endregion
20 
21 #region cookie的清除,注意cookie没有移除等方法,只能设置过期时间
22 if (myCookie1 != null)
23 {
24     myCookie1.Expires = DateTime.Now.AddMinutes(-1);//设置过过期
25     context.Response.Cookies.Add(myCookie1);
26 }
27 #endregion

3:cookie的特点:

  • A:因为cookie是存在客户端,所以不能有敏感信息,而且cookie推荐加密
  • B:因为每次请求都提交,这个是浏览器的特性,所以cookie不能太大,否则会影响性能
  • C:可以不指定expiretime,这样就可以存浏览器内存,然后关闭浏览器就cookie就丢失了
  • E:如果想存在硬盘就指定expiretime,如存在硬盘,以后想清空就修改有效期,否则不会丢失
  • F:cookie是跟浏览器有关系的,同一个浏览器登陆能覆盖,因为一个浏览器cookie只有一个地方存储,不同的浏览器登陆就不会覆盖,另外无痕模式是不会覆盖的
  • G:cookie是不跨域的

七:http协议:超文本传输协议,也就是个文本传输的规范;浏览器/客户端遵循;服务端也遵循,那么就可以发起交互了,具体就是靠文本来传输的,其实文本就是按照规范来拼接好的一连串字符串。具体请求如下图

跨域:浏览器A域名去访问B域名的东西,但是浏览器限制了跨域的请求,如果想要解决,就是服务响应的时候,增加响应头original-

 

八:Cookie跟Session的关系

是因为Http协议是无状态的,因此但是后面又想客户端跟服务器端进行交互,所以就产生的cookie跟session,具体他们之间交互的过程请看下图:

所以第一次客户访问会产生一个sessionid,然后写在cookie中,等下次客户再访问时,会把cookie中的sessionid带上,这样就晓得该客户的一些行为。

注意:sessionid会存在cookie中,那如果客户端把cookie禁用掉,那session还生效吗?答案是否定的,如果想要生效,必须通过URL或者隐藏文本框等其它渠道来解决。

 

Guess you like

Origin www.cnblogs.com/loverwangshan/p/11228409.html