欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

ASP.NET?Core管理應(yīng)用程序狀態(tài)

 更新時(shí)間:2022年04月13日 11:36:36   作者:Ruby_Lu  
這篇文章介紹了ASP.NET?Core管理應(yīng)用程序狀態(tài)的方法,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

在ASP.NET Core中,由多種途徑可以對(duì)應(yīng)用程序狀態(tài)進(jìn)行管理,使用哪種途徑,由檢索狀態(tài)的時(shí)機(jī)和方式?jīng)Q定。

應(yīng)用程序狀態(tài)指的是用于描述當(dāng)前狀況的任意數(shù)據(jù)。包括全局和用戶特有的數(shù)據(jù)。

開發(fā)人員可以根據(jù)不同的因素來選擇不同的方式存儲(chǔ)狀態(tài)數(shù)據(jù):

  • 數(shù)據(jù)需要存儲(chǔ)多久
  • 數(shù)據(jù)有多大
  • 數(shù)據(jù)的格式是什么
  • 數(shù)據(jù)是否可以序列化
  • 數(shù)據(jù)有多敏感
  • 數(shù)據(jù)能否保存在客戶端

 1.可選方式

1.HttpContext.Items

當(dāng)數(shù)據(jù)僅用于一個(gè)請(qǐng)求中時(shí),用Items集合存儲(chǔ)時(shí)最好的方式。數(shù)據(jù)將在每個(gè)請(qǐng)求結(jié)束之后丟棄。它是組件和中間件在一個(gè)請(qǐng)求中的不同時(shí)間點(diǎn)金總互相通信的最佳手段。

HttpContext抽象提供了一個(gè)簡單的IDictionary<object,object>類型的字典集合,就是Items。在每個(gè)請(qǐng)求中,這個(gè)集合從HttpRequest開始就可以使用,直到請(qǐng)求結(jié)束丟棄。要想存取集合,可以直接賦值和根據(jù)鍵查詢。

app.Use(async (context,next) =>
            {
                context.Items["isExist"] = true;
                await next.Invoke();
            });

            //在之后的管道查詢值
            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Is Exist:"+context.Items["isExist"]);
            });

2.QueryString 和 Post

在查詢字符串(QueryString )中添加值,或利用Post發(fā)送數(shù)據(jù),可以將一個(gè)請(qǐng)求的狀態(tài)數(shù)據(jù)提供給另一個(gè)請(qǐng)求。這不適合敏感數(shù)據(jù),因?yàn)檫@需要將數(shù)據(jù)發(fā)送到客戶端,然后再發(fā)送給服務(wù)器。這種方法也只適用于少量數(shù)據(jù)。用戶提交的數(shù)據(jù)是無法預(yù)期的,帶查詢字符串的網(wǎng)址很容易泄露,所以要避免跨網(wǎng)站請(qǐng)求偽裝攻擊(CSRF)。

3.Cookies

與狀態(tài)有關(guān)的小量數(shù)據(jù)可以存儲(chǔ)在Cookies中。他們會(huì)隨每次請(qǐng)求被發(fā)送到客戶端。應(yīng)該只使用一個(gè)標(biāo)識(shí)符,真正的數(shù)據(jù)存儲(chǔ)在服務(wù)端,服務(wù)端的數(shù)據(jù)與這個(gè)標(biāo)識(shí)關(guān)聯(lián)。

4.Session

會(huì)話存儲(chǔ)依靠一個(gè)基于Cookie的標(biāo)識(shí)符來訪問與給定瀏覽器相關(guān)的會(huì)話數(shù)據(jù)。一個(gè)會(huì)話可以與多個(gè)Cookie關(guān)聯(lián)。

5.Cache

緩存提供了一種方法,用自定義的鍵對(duì)應(yīng)用程序數(shù)據(jù)進(jìn)行存儲(chǔ)和檢索。它提供了一套基于時(shí)間和其他因素使緩存過期的規(guī)則。

6.其他

還可以使用EF和數(shù)據(jù)庫等進(jìn)行存儲(chǔ)應(yīng)用程序狀態(tài)。

2.使用Session

首先要安裝Microsoft.AspNetCore.Session安裝包。然后在Startup類中配置。Session是基于IDistributedCache構(gòu)建的,因此必須先配置好Session,否則會(huì)報(bào)錯(cuò)。

services.AddDistributedMemoryCache();
            services.AddSession(options =>
            {
                options.Cookie.Name = "Test.Session";
                options.IdleTimeout = TimeSpan.FromSeconds(10);
            });

ASP.NET 提供了IDistributedCache的多種實(shí)現(xiàn),in-memory是其中之一。上面采用in-memory,需要先安裝Microsoft.Extensions.Caching.Memory,然后添加上面代碼。

最后在Configure中調(diào)用 app.UseSession(),需要在app.UseMvc使用之前調(diào)用。

(1)實(shí)現(xiàn)細(xì)節(jié)

Session利用一個(gè)cookie來跟蹤和區(qū)分不同瀏覽器發(fā)出的請(qǐng)求。默認(rèn)情況下,這個(gè)cookie被命名為“.ASP.Session”,并使用路徑“/”。默認(rèn)情況下,這個(gè)cookie不指定域,而且對(duì)于頁面的客戶端腳本是不可使用的,因?yàn)镃ookieHttpOnly默認(rèn)為True。

其他的值可以通過SessionOptions配置:   

services.AddSession(options =>
            {
                options.Cookie.Name = "Test.Session";
                options.IdleTimeout = TimeSpan.FromSeconds(10);
            });

IdleTimeout 在服務(wù)端決定過期時(shí)間,session的過期時(shí)間是獨(dú)立于cookie的。

(2)ISession

安裝和配置好session之后,就可以通過HttpContext的一個(gè)名為Session,類型為ISession的屬性來引用會(huì)話。

public interface ISession
    {
        //
        // 摘要:
        //     Indicate whether the current session has loaded.
        bool IsAvailable { get; }
        //
        // 摘要:
        //     A unique identifier for the current session. This is not the same as the session
        //     cookie since the cookie lifetime may not be the same as the session entry lifetime
        //     in the data store.
        string Id { get; }
        //
        // 摘要:
        //     Enumerates all the keys, if any.
        IEnumerable<string> Keys { get; }

        //
        // 摘要:
        //     Remove all entries from the current session, if any. The session cookie is not
        //     removed.
        void Clear();
        //
        // 摘要:
        //     Store the session in the data store. This may throw if the data store is unavailable.
        Task CommitAsync(CancellationToken cancellationToken = default(CancellationToken));
        //
        // 摘要:
        //     Load the session from the data store. This may throw if the data store is unavailable.
        Task LoadAsync(CancellationToken cancellationToken = default(CancellationToken));
        //
        // 摘要:
        //     Remove the given key from the session if present.
        //
        // 參數(shù):
        //   key:
        void Remove(string key);
        //
        // 摘要:
        //     Set the given key and value in the current session. This will throw if the session
        //     was not established prior to sending the response.
        //
        // 參數(shù):
        //   key:
        //
        //   value:
        void Set(string key, byte[] value);
        //
        // 摘要:
        //     Retrieve the value of the given key, if present.
        //
        // 參數(shù):
        //   key:
        //
        //   value:
        bool TryGetValue(string key, out byte[] value);
    }

因?yàn)镾ession是建立在IDistributedCache之上的,所以總是需要序列化被存儲(chǔ)的對(duì)象實(shí)例。因此,這個(gè)接口是使用byte[]而不是直接使用object。string 和 int32 的簡單類型可以直接使用:

HttpContext.Session.SetInt32("key",123);
            HttpContext.Session.GetInt32("key");

存儲(chǔ)對(duì)象需要先把對(duì)象序列化為一個(gè)byte[]字節(jié)流。需要使用MemoryStream 和 BinaryFormatter

/// <summary> 
        /// 將一個(gè)object對(duì)象序列化,返回一個(gè)byte[]         
        /// </summary> 
        /// <param name="obj">能序列化的對(duì)象</param>         
        /// <returns></returns> 
        public static byte[] ObjectToBytes(object obj)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                IFormatter formatter = new BinaryFormatter(); formatter.Serialize(ms, obj); return ms.GetBuffer();
            }
        }
        /// <summary> 
        /// 將一個(gè)序列化后的byte[]數(shù)組還原         
        /// </summary>
        /// <param name="Bytes"></param>         
        /// <returns></returns> 
        public static object BytesToObject(byte[] Bytes)
        {
            using (MemoryStream ms = new MemoryStream(Bytes))
            {
                IFormatter formatter = new BinaryFormatter(); return formatter.Deserialize(ms);
            }
        }

到此這篇關(guān)于ASP.NET Core管理應(yīng)用程序狀態(tài)的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論