C# 操作Redis

关于Redis的安装和使用可以看本人Redis系列,这里就不在赘述了。

这里主要是C#操作redis。

1.在VS中利用NuGet安装ServiceStack.Redis,这是微软提供已经封装好的对redis操作类。包含4个dll

 

 2.自定义redis操作类 redisHelp

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication1.model
{
    /// <summary>
    /// Redis操作类
    /// </summary>
    public class redisHelp
    {

        public static ServiceStack.Redis.RedisClient client = new ServiceStack.Redis.RedisClient("127.0.0.1", 6379);

        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>

        public string getValue(string key)
        {
            return client.Get<string>(key);
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void setVaule(string key,string value)
        {
            client.Set<string>(key,value);
        }
    }
}
复制代码

3.测试数据插入和读取

复制代码
using JWT.MvcDemo.Help;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using WebApplication1.model;

namespace JWT.MvcDemo.App_Start
{
    public class MyAuthorizeAttribute : AuthorizeAttribute
    {


        private readonly string TimeStamp = ConfigurationManager.AppSettings["TimeStamp"];


        /// <summary>
        /// 验证入口
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
        }


        /// <summary>
        /// 验证核心代码
        /// </summary>
        /// <param name="httpContext">fbc8ZBLd5ZbtCogcY9NUVV4HZbPln1lb</param>
        /// <returns></returns>
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            redisHelp client = new redisHelp();


            //前端请求api时会将token存放在名为"auth"的请求头中
            var authHeader = httpContext.Request.Headers["auth"];
            if (authHeader == null)
                return false;

            //请求参数
            string requestTime = httpContext.Request["rtime"]; //请求时间经过DESC签名
            if (string.IsNullOrEmpty(requestTime))
                return false;

            //模拟生成rtime 时间戳,即登录的时间,加密.
            string r= DESCryption.Encode(DateTime.Now.ToString());
            requestTime = r;
            //插入redis
            client.setVaule(authHeader + ".rtime", r); //登录时间
            client.setVaule(authHeader+".UserName", "admin");//登录账号
            client.setVaule(authHeader + ".Pwd", "123");//登录密码

            //请求时间RSA解密后加上时间戳的时间即该请求的有效时间
            DateTime Requestdt = DateTime.Parse(DESCryption.Decode(requestTime)).AddMinutes(int.Parse(TimeStamp));
            DateTime Newdt = DateTime.Now; //服务器接收请求的当前时间

            if (Requestdt < Newdt)
            {
                return false;
            }
            else
            {
                if (authHeader != null)
                {
                    //进行其他操作
                    var userinfo = JwtHelp.GetJwtDecode(authHeader);
                    //举个例子  生成jwtToken 存入redis中    
                    //这个地方用jwtToken当作key 获取实体val   然后看看jwtToken根据redis是否一样

                    string UserName = client.getValue(authHeader + ".UserName");
                    string Pwd= client.getValue(authHeader + ".Pwd");

                    if (userinfo.UserName == UserName && userinfo.Pwd == Pwd)
                        return true;
                }

            }

            return false;
        }

        /// <summary>
        /// 验证失败处理
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            base.HandleUnauthorizedRequest(filterContext);
            filterContext.Result = new RedirectResult("/Error");
            filterContext.HttpContext.Response.Redirect("/Home/Error");
        }


    }
}
复制代码

posted @ 2022-10-30 10:07  心冰之海  阅读(5201)  评论(0编辑  收藏  举报