在Web Api使用Session

起因

在公司项目没使用过Web API,一直都是在使用WCF,今天建了一个Web API(Asp.Net Core)项目,使用到Session了,发现是无法使用的.是因为从Asp.Net到Asp.Net Core时,抛弃了全家桶,改为按需使用(当你需要使用的时候,再去配置).

建一个空Web API项目

[HttpGet]
public WeatherForecast Get()
{
    byte[] val;
    HttpContext.Session.TryGetValue("key", out val);  //根据key从Session获取数据


    return new WeatherForecast();
}

运行之后,发现报错了,如下图.

Asp.Net Core Web Api默认没有开启Session,无法直接使用Session

突然想起Web Api默认应该开启Session功能.在Startup.cs文件开启Session,修改Startup.cs文件.

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.AddControllers();

        #region 开启Session

        services.AddDistributedMemoryCache();
        services.AddSession(x =>
        {
            x.IdleTimeout = TimeSpan.FromHours(1); //设置过期时间为一个小时
        }); 

        #endregion
    }

    // 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();   //使用Session

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

给Session增加扩展方法

因为.Net Core Session默认的方法使用不是很方便,所以增加几个扩展方法,让我们使用的时候能方便一些.

namespace Microsoft.AspNetCore.Http
{
    //这里使用.Net Core自带的序列化json组件,主要是方便
    //正式项目中,还是使用比较均衡Json.Net组件
    using System.Text.Json;
    public static class SessionExtension
    {
        /// <summary>
        /// 将泛型数据放入Session中 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="session"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void Set<T>(this ISession session, string key, T value)
        {
            session.SetString(key, JsonSerializer.Serialize(value));

        }

        /// <summary>
        /// 从Session获取泛型数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="session"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static T Get<T>(this ISession session, string key)
        {
            var value = session.GetString(key);
            return value == null ? default(T) : JsonSerializer.Deserialize<T>(value);
        }

        /// <summary>
        /// 从Session获取数据,返回是否成功
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="session"></param>
        /// <param name="key"></param>
        /// <param name="val"></param>
        /// <returns></returns>
        public static bool TryGetValue<T>(this ISession session, string key, out T val)
        {
            var value = session.GetString(key);
            if (value == null)
            {
                val = default(T);
                return false;
            }
            else
            {
                val = JsonSerializer.Deserialize<T>(value);
                return true;
            }
        }
    }
}

使用:

[HttpGet]
public WeatherForecast Get()
{
    WeatherForecast weather;
    HttpContext.Session.Set("test", new WeatherForecast() { Summary = "11", Date = DateTime.Now, TemperatureC = 111 });

    if (HttpContext.Session.TryGetValue("test", out weather))
    {
        return weather;
    }
    else
    {

        return new WeatherForecast();
    }
}
秋风 2019-12-20