• Asp.Net Core3.x中使用Cookie


    在Asp.Net中使用Cookie相对容易使用,Request和Response对象都提供了Cookies集合,要记住是从Response中存储,从Request中读取相应的cookie。Asp.Net Core3.x中Cookie相对不是直接使用,Asp.Net属于大礼包方式把你要的不要的通通给你(比较臃肿_(¦3」∠)_),而在Asp.Net Core3.x中属于自选行的项目中需要什么自己引用什么(比较清爽简洁(#.#)),我们今天就说说在Asp.Net Core中如何使用Cookie。
    一、在Asp.Net Core项目中Startup.cs中注入Cookie前置条件
    在ConfigureServices方法中注入 services.AddHttpContextAccessor()方法 在Asp.Net Core3.x中HttpContext在接口IHttpContextAccessor中set、get 。
    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.AddHttpContextAccessor();//配置Cookie HttpContext
            services.AddTransient<ICookie, Cookie>();//IOC配置 方便项目中使用
            services.AddTransient(typeof(Config));//基础配置
             
        }
    
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Index");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();
    
            app.UseRouting();
    
            app.UseAuthorization();
    
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
    

    二、创建Cookie类
    创建接口类ICookie
    public interface ICookie
    {
    void SetCookies(string key, string value, int minutes = 300);

        /// <summary>
        /// 删除指定的cookie
        /// </summary>
        /// <param name="key">键</param>
        void DeleteCookies(string key);
    
        /// <summary>
        /// 获取cookies
        /// </summary>
        /// <param name="key">键</param>
        /// <returns>返回对应的值</returns>
        string GetCookies(string key);
        
    }
    

    要清楚知道在Asp.Net Core3.x中HttpContext在IHttpContextAccessor中。IHttpContextAccessor程序集引用Microsoft.AspNetCore.Http 项目下没有的可以在NuGet包管理器中添加。
    public class Cookie : ICookie
    {
    private readonly IHttpContextAccessor _httpContextAccessor;

        public Cookie(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }
        /// <summary>
        /// 设置本地cookie
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>  
        /// <param name="minutes">过期时长,单位:分钟</param>      
        public void SetCookies(string key, string value, int minutes = 300)
        {
            _httpContextAccessor.HttpContext.Response.Cookies.Append(key, value, new CookieOptions
            {
                Expires = DateTime.Now.AddMinutes(minutes)
            });
        }
    
        /// <summary>
        /// 删除指定的cookie
        /// </summary>
        /// <param name="key">键</param>
        public void DeleteCookies(string key)
        {
            _httpContextAccessor.HttpContext.Response.Cookies.Delete(key);
        }
    
        /// <summary>
        /// 获取cookies
        /// </summary>
        /// <param name="key">键</param>
        /// <returns>返回对应的值</returns>
        public string GetCookies(string key)
        {
            _httpContextAccessor.HttpContext.Request.Cookies.TryGetValue(key, out string value);
            if (string.IsNullOrEmpty(value))
                value = string.Empty;
            return value;
        } 
    }
    

    三、在项目中使用Cookie 在HomeController我们直接使用IOC方式使用Cookie 当然要在Startup注入
    public class HomeController : Controller
    {
    private readonly ILogger _logger;

        private readonly ICookie _cookie;
    
        private readonly Config _config;
        public HomeController(ILogger<HomeController> logger, ICookie cookie, Config config)
        {
            _logger = logger;
            this._cookie = cookie;
            this._config = config;
        }
    
        public IActionResult Index()
        {
            _cookie.SetCookies(_config.CookieName(), "CookieValue");
    
            string CookieValue = _cookie.GetCookies(_config.CookieName());
    
            _cookie.DeleteCookies(_config.CookieName());
    
            return View();
        }
    
        public IActionResult Privacy()
        {
            return View();
        }
    
        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
    

    总结
    1)、使用Cookie首先在Startup中注入AddHttpContextAccessor()
    2)、创建Cookie公用类实现Cookie的增删查
    3)、项目中在Startup中注入Cookie在控制器中IOC方式使用Cookie

  • 相关阅读:
    C#中 Thread,Task,Async/Await,IAsyncResult 的那些事儿!
    Java8的新特性以及与C#的比较
    点旋转坐标变换
    vc++返回模块路径
    为什么不要 "lock(this)" ? lock object 并是readonly(转载)
    《黄帝内经》要义
    C++多线程编程简单实例
    c++ 获取文件大小
    c# 获取文件夹大小
    自动驾驶仿真工具的下载与安装
  • 原文地址:https://www.cnblogs.com/moxuanshang/p/13607988.html
Copyright © 2020-2023  润新知