亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 ASP.NET Core 2.0 存儲和恢復 cookie?

如何使用 ASP.NET Core 2.0 存儲和恢復 cookie?

C#
慕哥9229398 2021-12-05 16:33:51
我使用 ASP.NET Core 創建了一個示例 Web 應用程序來測試 cookie 的存儲和檢索。不幸的是,我無法存儲 cookie。我將首先請求一個 IndexA 操作來存儲 cookie。代碼運行時沒有任何錯誤,但是當我請求 IndexB 操作時。沒有找到指定的值這是 IndexA 操作:public IActionResult IndexA(){   Response.Cookies.Append("mykey", "myvalue",    new CookieOptions()    {        Expires = DateTime.Now.AddMinutes(10)    });  return View();}這是 IndexB 操作:public IActionResult IndexB(){   var cookie = Request.Cookies["mykey"];   return View();}這是啟動類:public class Startup{    public Startup(IConfiguration configuration)    {        Configuration = configuration;    }    public IConfiguration Configuration { get; }    // This method gets called by the runtime. Use this method to add services to the container.    public void ConfigureServices(IServiceCollection services)    {        services.Configure<CookiePolicyOptions>(options =>        {        // This lambda determines whether user consent for non-essential cookies is needed for a given request.        options.CheckConsentNeeded = context => true;            options.MinimumSameSitePolicy = SameSiteMode.None;        });        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);    }    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.    public void Configure(IApplicationBuilder app, IHostingEnvironment env)    {        if (env.IsDevelopment())        {            app.UseDeveloperExceptionPage();        }        else        {            app.UseExceptionHandler("/Home/Error");        }        app.UseStaticFiles();        app.UseCookiePolicy();        app.UseMvc(routes =>        {            routes.MapRoute(                name: "default",                template: "{controller=Home}/{action=Index}/{id?}");        });    }}
查看完整描述

3 回答

?
慕的地6264312

TA貢獻1817條經驗 獲得超6個贊

我認為這可能與 ASP.NET Core 2.1 附帶的 GDPR 相關功能有關。我的理解是,它允許網站定義哪些 cookie 對瀏覽器來說是必不可少的,而那些非必需的則不會被發送。


我能想到的第一件事就是簡單地刪除對非必要 cookie 的同意檢查。不要在生產中這樣做,因為你可能會違反規定!. 改變:


services.Configure<CookiePolicyOptions>(options =>

{

    options.CheckConsentNeeded = context => true;

    options.MinimumSameSitePolicy = SameSiteMode.None;

});


services.Configure<CookiePolicyOptions>(options =>

{

    // No consent check needed here

    options.CheckConsentNeeded = context => false;

    options.MinimumSameSitePolicy = SameSiteMode.None;

});

解決此問題的第二種可能方法是將您的 cookie 聲明為必不可少的,因此無論同意檢查結果如何,您的 cookie 都將被發送到瀏覽器。為此,請更改:


Response.Cookies.Append(

  "mykey",

  "myvalue",

  new CookieOptions()

  {

      Expires = DateTime.Now.AddMinutes(10)

  });


Response.Cookies.Append(

  "mykey",

  "myvalue",

  new CookieOptions()

  {

      Expires = DateTime.Now.AddMinutes(10),

      // Marking the cookie as essential

      IsEssential = true

  });


查看完整回答
反對 回復 2021-12-05
?
慕斯王

TA貢獻1864條經驗 獲得超2個贊

我正在使用 ASP.NET 核心 2.2。這是我在 ConfigureServices(IServiceCollection services) 中將 HttpContextAccessor 注入我的控制器的內容。


    public void ConfigureServices(IServiceCollection services)

    {

        services.AddMvc();

        //... some code

        //services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

        services.AddHttpContextAccessor();

    }

這是我的控制器中的內容:


    private readonly IHttpContextAccessor _httpContextAccessor;


    public MySomethingController(IHttpContextAccessor httpContextAccessor)

    {

        //... some code

        this._httpContextAccessor = httpContextAccessor;

    }

下面是 Action 方法的代碼:


[HttpGet]

    public IActionResult SomethingToDo()

    {

        //... some code for my controller


        //Section for handling cookies

        //set the key value in Cookie  

        SetCookie("MyOwnKey", "Hello World from cookie", 15.0);


        //read cookie from IHttpContextAccessor 

        string cookieValueFromContext = _httpContextAccessor.HttpContext.Request.Cookies["MyOwnKey"];

        //or 

        string cookieValueFromRequest = GetCookie("MyOwnKey");


        //Delete the cookie object  

        //RemoveCookie("MyOwnKey");


        ViewData["CookieFromContext"] = cookieValueFromContext;

        ViewData["CookieFromRequest"] = cookieValueFromRequest;


        return View();

    }

然后我有以下方法:


    public string GetCookie(string key)

    {

        return Request.Cookies[key];

    }


    public void SetCookie(string key, string value, double? expireTime)

    {

        CookieOptions option = new CookieOptions();

        if (expireTime.HasValue)

            option.Expires = DateTime.Now.AddMinutes(expireTime.Value);

        else

            option.Expires = DateTime.Now.AddMilliseconds(1);

        Response.Cookies.Append(key, value, option);

    }


    public void RemoveCookie(string key)

    {

        Response.Cookies.Delete(key);

    }

我能夠在另一個控制器中看到 cookie 值并將其傳遞給視圖。我在家庭控制器中有這個:


...

    private readonly IHttpContextAccessor _httpContextAccessor;

    private readonly IHostingEnvironment _hostingEnvironment;



    public HomeController(IHostingEnvironment hostingEnvironment, IHttpContextAccessor httpContextAccessor)

    {

        this._hostingEnvironment = hostingEnvironment;

        this._httpContextAccessor = httpContextAccessor;

    }


    public IActionResult Index()

    {

        //read cookie from IHttpContextAccessor 

        string cookieValueFromContext = _httpContextAccessor.HttpContext.Request.Cookies["MyOwnKey"];

        ViewData["CookieFromContext"] = cookieValueFromContext;


        return View();

    }


查看完整回答
反對 回復 2021-12-05
?
皈依舞

TA貢獻1851條經驗 獲得超3個贊

一個控制器暴露 HttpContext.Response.Cookies... 不需要通過 ConfigureServices 方法使用依賴注入,也不需要向控制器添加額外的屬性。只需調用 HttpContext.Response.Cookies.Append(...);


查看完整回答
反對 回復 2021-12-05
  • 3 回答
  • 0 關注
  • 223 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號