DotNetCore會話探索篇

Walk in loosing發表於2020-10-18

怎麼把在Asp.Net的會話實現遷移到DotNetCore。

1.首先修改Startup加入會話支援

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace WebTow
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDistributedMemoryCache();

            services.AddSession(options =>
            {
                //使用會話加的
                options.IdleTimeout = TimeSpan.FromSeconds(1800);
                options.Cookie.HttpOnly = true;
                options.Cookie.IsEssential = true;
            });
        }

        // 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();
            }

            app.UseRouting();
            //使用會話
            app.UseSession();
            //註冊中介軟體
            app.UseMiddleware<MianMiddleware>();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("Hello World!");
                });
            });
        }
    }
}

2.設定會話

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;

namespace WebTow
{
    /// <summary>
    /// 執行請求基類
    /// </summary>
    public class BaseHttpHandler : IBaseHttpHandler
    {
        /// <summary>
        /// 系統內嵌的超級使用者
        /// dhcc賬戶不能被刪除
        /// dhcc不能被鎖定
        /// dhcc具有所有的選單
        /// dhcc具有所有的功能
        /// dhcc密碼不能被修改
        /// </summary>
        public static string DHCC = "dhcc";

        /// <summary>
        /// 所有的請求引數
        /// </summary>
        private HttpContext contex;

        /// <summary>
        /// 所有的響應引數
        /// </summary>
        private HttpResponse response;

        /// <summary>
        /// 所有的請求引數
        /// </summary>
        private HttpRequest request;

        /// <summary>
        /// 會話物件
        /// </summary>
        private ISession session;

        

        /// <summary>
        /// 所有的請求引數
        /// </summary>
        public HttpRequest Request
        {
            get
            {
                return request;
            }
            set
            {
                request = value;
            }
        }

        /// <summary>
        /// 所有的響應引數
        /// </summary>
        public HttpResponse Response
        {
            get
            {
                return response;
            }
            set
            {
                response = value;
            }
        }

        /// <summary>
        /// 所有的請求引數
        /// </summary>
        public ISession Session
        {
            get
            {
                return session;
            }
            set
            {
                session = value;
            }
        }

        /// <summary>
        /// 過載方法
        /// </summary>
        /// <param name="context">上下文</param>
        public void ProcessRequest(HttpContext context)
        {
            //賦值私有變數
            request = context.Request;
            response = context.Response;
            session = context.Session;
            session.SetString("USR","{\"Name\":\"張聯珠\"}");
            //是否是訪問登入介面
            string path = Request.GetDisplayUrl();
            //判斷是否訪問登陸介面
            bool loginFlag = path.ToLower().IndexOf("login.ashx") > -1;


            //統一處理方法呼叫
            string result = string.Empty;
            try
            {
                //執行要呼叫的方法
                result = ProcessRequestReflect();
                //否則輸出結果
                Write(result);
                return;
            }
            catch (Exception e)
            {
                Write(e.Message);
                return;
            }
        }

        /// <summary>
        /// 前臺的統一輸出方法
        /// </summary>
        /// <param name="message"></param>
        public void Write(string message)
        {
            this.Response.WriteAsync(message);
        }


        /// <summary>
        /// 呼叫需要呼叫的所有方法 
        /// </summary>
        /// <returns></returns>
        private string ProcessRequestReflect()
        {
            //獲得前臺傳入的要呼叫的方法名稱
            string method = Request.Query["Method"];
            //方法名稱不為空,找到並執行方法
            if (!string.IsNullOrEmpty(method))
            {
                //根據名稱獲得方法資訊
                MethodInfo methodInfo = this.GetType().GetMethod(method, BindingFlags.Instance | BindingFlags.IgnoreCase | BindingFlags.Public);
                //沒找到方法就丟擲錯誤資訊
                if (methodInfo == null)
                {
                    return "未找到後臺方法“" + method + "”!";
                }
                //執行找到的方法,並返回結果
                return (string)methodInfo.Invoke(this, null);
            }
            else
            {
                return "方法名Method不能為空!";
            }
        }

    }
}

3.獲取會話

using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebTow.Test.ashx
{
    public class TestAshx:BaseHttpHandler
    {
        public string GetData()
        {
            //得到會話的使用者資訊
            string usr = Session.GetString("USR");
            return "我是ashx裡實現方法,這是我給前端返回的引數。會話資訊:" + usr;
        }
    }
}

using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebTow.Test.ashx
{
    public class TestTowAshx : BaseHttpHandler
    {
        public string GetData()
        {
            //得到會話的使用者資訊
            string usr=Session.GetString("USR");
            return "我是ashx裡實現方法2,這是我給前端返回的引數。會話資訊:"+ usr;
        }
    }
}

執行效果
在這裡插入圖片描述

在這裡插入圖片描述

相關文章