加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

C#CORE3.1的WEBAPI中SESSION使用

(2022-05-05 19:22:02)
标签:

c

session

core3.1

webapi

分类: 软件开发
服务器端
1.NUGET 加载PACKAGE
使用NUGET的URL 
https://nuget.cdn.azure.cn/v3/index.json
PACKAGE名:
Microsoft.AspNetCore.Session
Microsoft.AspNetCore.HttpOverrides
2. 添加Session配置服务(Startup.cs)
 public void ConfigureServices(IServiceCollection services)
               
            services.AddControllers();
            // 指定Session保存方式:分发内存缓存
            services.Configure(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => false;//这里要改为false,默认是true,true的时候session无效
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddDistributedMemoryCache();
            services.AddSession(option =>
            {
                option.IOTimeout = TimeSpan.FromHours(1);
                option.IdleTimeout = TimeSpan.FromHours(1);
                option.Cookie.HttpOnly = true;
                // Make the session cookie essential
                option.Cookie.IsEssential = true;
                option.Cookie.Name = "XMECG";
                //默认cookie如果没有信息,会被清空,导致sessionid改变,所以先给个名字
            });
            services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
            // SESSION 结束
        }
 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
          ............
            app.UseAuthorization();
          //启动SESSION
            app.UseSession();
            app.UseCookiePolicy();
   //支持获取IP地址
            app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto });
  //End Sesson 
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
3. 在Controller中使用Session
   //设置
   HttpContext.Session.SetString("USERID", "888");
、//获取
            if (HttpContext.Session.TryGetValue("USERID", out byte[] bytes))
            {
                theUserId = Encoding.UTF8.GetString(bytes);
            }
客户端
1.定义CookieContainer
        private static CookieContainer cookie  = new CookieContainer();
2.POST代码
在HTTP POST时要包括CookieContainer,否则会认为一个新的SESSION
public int   APITest()
{
  string url = "http://xxx/API/HelloWorld";
  string theText = "TEST";
           byte[] bs = Encoding.UTF8.GetBytes(theText);
            HttpWebRequest theRequest = (HttpWebRequest)HttpWebRequest.Create(url);
            theRequest.Method = "POST";
            theRequest.ContentType = "application/json;charset=utf-8";
            theRequest.ContentLength = bs.Length;
            theRequest.Headers.Set("Cookie", "cookie");
            theRequest.CookieContainer = cookie;
            using (Stream reqStream = theRequest.GetRequestStream())
            {
                reqStream.Write(bs, 0, bs.Length);
                reqStream.Close();
            }
            using (Stream reqStream = theRequest.GetRequestStream())
            {
                reqStream.Write(bs, 0, bs.Length);
                reqStream.Close();
            }
            using (WebResponse wr = theRequest.GetResponse())
            {
                Stream theResponseStream = wr.GetResponseStream();
                StreamReader theReader = new StreamReader(theResponseStream);
                string theOutPut = theReader.ReadToEnd();
                System.Text.UTF8Encoding converter = new System.Text.UTF8Encoding();
                string theBase642 = converter.GetString(Convert.FromBase64String(theOutPut));
             }

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有