2.MVC大项目第二天(登录)
1:统一的登录验证: 创建一个继承了ActionFilterAttribute的特性标签重写里面的OnActionExecuting方法
a:首先判断session中是否有用于登录的对象 如果没有则直接提示用户还没登录返回登录页面
b:如果session中有需要登录的对象
b1:判断cookie中是否有对应的用户表的主键 如果没有则直接返回 如果有那么根据主键获取到对应的实例对象 存进session中
统一登录总结:
1:统一登录这个标签需要设置为全局在Application_Start的一个方法中注册全局
2:注意登录页面和验证码的页面需要不要进行统一的登录验证 所以我们需要创建自定义标签 继承Attribute 最后在统一登录验证进行判断
3:首先我们需要判断session:用户是否登录过 再判断用户是否勾选了保存登录信息
4:我们需要实现接口对象的时候是获取缓存中储存的autofac容器 所以我们创建autofac容器的时候就需要将其储存在缓存中
验证码例子:
[SkipCheckLogin]
public class VCodeController : Controller
{
public ActionResult GetVCode()
{
string vcode = Vcode(1);
Session[Keys.Vcode] = vcode;
byte[] imgbuffer; //注意因为我们通过fileResult返回的需要是个数组
using (Image img=new Bitmap(65,25))
{
using (Graphics g=Graphics.FromImage(img))
{
g.Clear(Color.White);
g.DrawString(vcode, new Font("黑体", 14, FontStyle.Bold), new SolidBrush(Color.Red), 3, 4);
using (System.IO.MemoryStream ms=new System.IO.MemoryStream())
{
img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
imgbuffer = ms.ToArray();
}
}
}
return File(imgbuffer, "image/jpeg");
}
//创建验证码
Random r = new Random();
public string Vcode(int num)
{
string vcodestr = "23456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ";
string scode = string.Empty;
int length = vcodestr.Length;
for (int i = 0; i < num; i++)
{
scode += vcodestr[r.Next(length)];
}
return scode;
}
}
刷新验证码的方法
$("#vcodeimg").attr("src", '@Url.Action("Vcode", "Vcode")?rid=' + Math.random());
统一登录例子
//判断session中是否有值 如果有那么表示用户已经登录过了
if (filterContext.HttpContext.Session[Keys.Uinfo]!=null)
{
//从缓存中获取autofac的容器对象 在我们创建autofac的容器对象
IContainer autofac =CacheMgr.GetData<IContainer>(Keys.autofaccontainer);
//从autofac容器中获取IsysUserInfoServices的实现类的对象实例 我们首先需要向缓存中存入
IsysUserInfoServices userSer = autofac.Resolve<IsysUserInfoServices>();//我们可以理解为依赖注入
//根据主键id来获取对象实例
//获取用户的主键
string userid = filterContext.HttpContext.Request.Cookies[Keys.IsRemember].Value;
int uid = int.Parse(userid);
var userinfo = userSer.QueryWhere(c => c.uID == uid).FirstOrDefault();
//我们需要根据id来获取到对象实例 然后将对象的实例储存返回输入框中
if (userinfo!=null)
{
//将获取到的对象实例存进session中 到时我们登录的时候就不用继续输入了
filterContext.HttpContext.Session[Keys.Uinfo] = userinfo;
}
else
{
//否则跳转到登录页面
}
}
else
{
//表示用户没有登录 所以我们需要直接返回到登录页面
}
浙公网安备 33010602011771号