.NetCore【中间件】Cookie

Core默认并没有引入cookie,需要加入中间件才能使用

添加Cookie中间件

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace Thomerson.Gatlin.Midware
{
    public static class CookieMidware
    {
        public static IServiceCollection AddCookieMidware(this 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;
            });
            return services;
        }

        public static IApplicationBuilder UseCookieMidware(this IApplicationBuilder app)
        {
            app.UseCookiePolicy();
            return app;
        }
    }
}

3.StartUp中启用

            //Cookie 设置
            services.AddCookieMidware();

            //Cookie 设置
            app.UseCookieMidware();

4.Controller使用

using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc;

namespace Thomerson.Gatlin.Controllers
{
    /// <summary>
    /// Base API Controller
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    [EnableCors("AppDomain")]  //路由跨域设置  AppDomain = CORSMidware.PolicyName
    public class BaseAPIController : ControllerBase
    {
        /// <summary>
        /// Client 启用Cookie 网站首页启动时js调用
        /// </summary>
        [HttpPost]
        public void EnableCookie()
        {
            HttpContext.Features.Get<ITrackingConsentFeature>().GrantConsent();
        }

        #region Cookie


        protected void AddCookies(string key, string val)    //删除指定的cookie
        {
            Response.Cookies.Append(key, val
                //, new Microsoft.AspNetCore.Http.CookieOptions()
                //{
                //    HttpOnly = true,//后端只读,前端无法通过js获取cookie防止XXL攻击
                //    Secure = false          //安全模式,https
                //}
                );
        }

        protected void DeleteCookies(string key)    //删除指定的cookie
        {
            HttpContext.Response.Cookies.Delete(key);
        }

        protected string GetCookies(string key)     //获取指定的cookie
        {
            HttpContext.Request.Cookies.TryGetValue(key, out string value);
            if (string.IsNullOrEmpty(value))
                value = string.Empty;
            return value;
        }
        #endregion

    }
}

源码

posted on 2022-12-04 21:08  杏村牧童  阅读(137)  评论(0编辑  收藏  举报