zoukankan      html  css  js  c++  java
  • 【原创】基于Memcached 实现用户登录的Demo(附源码)

    一个简单的Memcached在Net中运用的一个demo。主要技术 Dapper+MVC+Memcached+sqlserver,

    开发工具为vs2015+Sql

    效果图如下:

     

    登录后

     

    解决方案

     主要实现代码

    using Model;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using website.Models;
    namespace website.Controllers
    {
        public class LoginController : Controller
        {
            // GET: Login
            BLL.Users service = new BLL.Users();
            public ActionResult Index()
            {
                return View();
            }
            [HttpPost]
            public ActionResult Login(string username,string password)
            {
                int count = 0;
                try
                { 
                    count=service.Count(" where username='"+username+"' and password='"+password+"' ");
                    
                    if (count == 0)
                    {
                        return Json(new { success = false, msg = "用户名或密码不正确" });
                    }
                    else
                    {
    
    
                       var loginUser = service.QueryList(" where username='" + username + "' and password='" + password + "' ").SingleOrDefault();
           
    
                        Guid sessionId = Guid.NewGuid();//申请了一个模拟的GUID:SessionId
    
                        //把sessionid写到客户端浏览器里
                        Response.Cookies["sessionId"].Value = sessionId.ToString();
    
                        //可以缓存model 也可缓存list
                        MemcacheHelper.Set(sessionId.ToString(), loginUser, DateTime.Now.AddMinutes(20));
                        return Json(new { success = true, msg = "登陆成功" });
                    }
                }
    
                catch(Exception ex)
                {
                    return Json(new { success = false, msg = ex.Message });
    
                }
    
            }
    
        }
    }
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using Model;
    using System.Net.Http;
    using website.Models;
    
    namespace website.Controllers
    {
        public class BaseController : Controller
        {
            BLL.Users service = new BLL.Users();
    
            protected string hostUrl = "";
            Users currentuser = new Users();
    
    
            public ActionResult Layout()
            {
                Users user = GetCurrentUser();
                ViewData["username"] = user.UserName;
                ViewData["TrueName"] = user.TrueName;
                return View("~/Views/Shared/_MyLayout.cshtml");
               // return View();
            }
    
            /// <summary>
            /// Action执行前判断
            /// </summary>
            /// <param name="filterContext"></param>
            protected override void OnActionExecuting(ActionExecutingContext filterContext)
            {
    
    
                base.OnActionExecuting(filterContext);
    
                //从cookie中获取登录的sessionId
                string sessionId = Request["sessionId"];
                if (string.IsNullOrEmpty(sessionId))
                {
                   
                    Response.Redirect("/Login/Index");
                }
    
                object obj = MemcacheHelper.Get(sessionId);
              
                Users user = obj as Users;
                if (user == null)
                {
                    Response.Redirect("/Login/Index");
                }
    
                currentuser = user;
                MemcacheHelper.Set(sessionId, user, DateTime.Now.AddMinutes(20));
    
            }
            
            /// <summary>
            /// 判断是否登录
            /// </summary>
            protected bool checkLogin()
            {
                //HttpCookie _cookie = httpContext.Request.Cookies["CookieUser"];
                if (this.Session["userinfo"] == null)
                {
                    return false;
                }
                return true;
            }
            /// <summary>
            /// 返回当前登录用户
            /// </summary>
            /// <returns></returns>
            protected Users GetCurrentUser()
            {            
                if (checkLogin())
                {
                    currentuser = service.QueryList(" where username='" + this.Session["userinfo"].ToString() + "'").SingleOrDefault(); 
                }
                return currentuser;
            }
    
            
        }
    }
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using Memcached.ClientLibrary;
    
    namespace website.Models
    {
        public static class MemcacheHelper
        {
            private static MemcachedClient mc;
    
            static MemcacheHelper()
            {
                String[] serverlist = { "127.0.0.1:11211" };
    
                // initialize the pool for memcache servers
                SockIOPool pool = SockIOPool.GetInstance("test");
                pool.SetServers(serverlist);
                pool.Initialize();
                mc = new MemcachedClient();
                mc.PoolName = "test";
                mc.EnableCompression = false;
                
            }
    
            public static bool Set(string key, object value,DateTime expiry){
                return mc.Set(key, value, expiry);
            }
    
            public static object Get(string key)
            {
                return mc.Get(key);
            }
        }
    }

    总结:自己练习的Demo,有很多地方不完善,欢迎指正!!

     https://yunpan.cn/c63VD4ekxn78b  访问密码 2f97

  • 相关阅读:
    ISC2016训练赛 phrackCTF--Classical CrackMe
    JCTF 2014 小菜一碟
    攻防世界--ReverseMe-120
    lstm torch
    pandas 处理 纽约签到数据集
    python datatime
    tf.keras 模型 多个输入 tf.data.Dataset
    python **kwarg和*args
    java 优先队列 大根堆
    python总结
  • 原文地址:https://www.cnblogs.com/hgmyz/p/5675269.html
Copyright © 2011-2022 走看看