红色部分为重点

1.webconfig配置

 <system.web>节点下添加
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" name=".userInfo" protection="All" path="/"></forms>
</authentication>
如果有如下节点则删除

<system.webServer>
<modules>
<remove name="FormsAuthentication" />
</modules>
</system.webServer>

2.<forms loginUrl="~/Account/Login  中的loginUrl的值的~不能省略
        public ActionResult Login(LoginViewModel login)
{
//验证账号密码
AspTaskServiceClient service = new AspTaskServiceClient(); //调用svc服务
if (service.IsLoginOk(login.UserId, Commen.Sha256(login.Password)))
{ AspUser user = service.GetUserInfo(login.UserId);
LoginViewModel userinfo = new LoginViewModel()
{
UserId = login.UserId,
Password = login.Password,
UserName = user.LoginUserName,
AspId = user.AspId,
IsAsp = user.IsAspUser ? "1" : "0"
}; FormsAuthentication.SetAuthCookie(JsonHelper.ToJsonString(userinfo), false); //设置cookies
if (Request.QueryString["ReturnUrl"] != null)
{
if (Request.QueryString["ReturnUrl"].Contains("LogOff"))
{ return RedirectToAction("../Task/TaskList");
}
else
{
return Redirect(Request.QueryString["ReturnUrl"]);
} } else return RedirectToAction("../Task/TaskList");
}
else
{
ModelState.AddModelError("", "正しくユーザー または パスワードを入力ください。");
return View(login);
} }

  

3读取cookies
        protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
{
if (string.IsNullOrWhiteSpace(HttpContext.Current.User.Identity.Name)) return false;
LoginViewModel userinfo=JsonHelper.ToObject<LoginViewModel>(HttpContext.Current.User.Identity.Name); AspTaskServiceClient service = new AspTaskServiceClient(); string _userId = userinfo.UserId;
string _password = userinfo.Password;
if (_userId == "" || _password == "") return false;
if (service.IsLoginOk(_userId, Commen.Sha256(_password)))
{
return true;
}
else
{
return false;
} }

  

附:JsonHelper.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json; namespace xxx.Serialization.Json
{
public class JsonHelper
{
public static string ToJsonString(object obj)
{
return JsonConvert.SerializeObject(obj);
} public static T ToObject<T>(string jsonString)
{
return JsonConvert.DeserializeObject<T>(jsonString);
}
}
}

  

sha256.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web; namespace xxx.Controllers
{
public class Commen
{
public static string Sha256(string plainText)
{
SHA256Managed _sha256 = new SHA256Managed();
byte[] _cipherText = _sha256.ComputeHash(Encoding.Default.GetBytes(plainText));
return Convert.ToBase64String(_cipherText);
}
}
}

  

4.action的cookie值传入到view的js文件

        public ActionResult TaskList()
{
ViewBag.cookies = User.Identity.Name;
return View();
}

  

   view里的js文件

如下

        function getUserInfo() {//获取当前用户
user = new Object();
var arrCookie = @Html.Raw(ViewBag.cookies);
if (arrCookie!=null) {
user.userId =arrCookie["UserId"];
user.userName = arrCookie["UserName"]
user.aspId =arrCookie["AspId"];
user.isAspUser = arrCookie["IsAsp"]== "1" ? true : false;
}
}

  5.退出登陆

1._LoginPartial.cshtml显示设置   必须添加引用

@using xxxx.Serialization.Json;
@using xxx.Models; @if (!string.IsNullOrWhiteSpace(User.Identity.Name))
{ using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
{
Html.AntiForgeryToken(); <ul class="nav navbar-nav navbar-right">
<li>
@Html.ActionLink(JsonHelper.ToObject<LoginViewModel>(User.Identity.Name).UserName + " 様", "", "", routeValues: null, htmlAttributes: new { title = "" })
</li>
<li><a href="javascript:document.getElementById('logoutForm').submit()">ログオフ</a></li> </ul>
}
}

  

  2.退出登陆清除cookies

        public ActionResult LogOff()
{ FormsAuthentication.SignOut(); return RedirectToAction("Login", "Account"); }

  

MVC Form验证 登陆和退出Cookies的设定和消除的更多相关文章

  1. ASP.NET MVC Form验证

    一.前言 关于表单验证,园子里已经有不少的文章,相信Web开发人员也都基本写过,最近在一个个人项目中刚好用到,在这里与大家分享一下.本来想从用户注册开始写起,但发现东西比较多,涉及到界面.前端验证.前 ...

  2. tornado web高级开发项目之抽屉官网的页面登陆验证、form验证、点赞、评论、文章分页处理、发送邮箱验证码、登陆验证码、注册、发布文章、上传图片

    本博文将一步步带领你实现抽屉官网的各种功能:包括登陆.注册.发送邮箱验证码.登陆验证码.页面登陆验证.发布文章.上传图片.form验证.点赞.评论.文章分页处理以及基于tornado的后端和ajax的 ...

  3. ASP.NET MVC Form表单验证与Authorize特性

    一.Form表单验证 1.基本概念 表单验证是一个基于票据(ticket-based)[也称为基于令牌(token-based)]的系统.当用户登录系统以后,会得到一个包含基于用户信息的票据(tick ...

  4. 本博文将一步步带领你实现抽屉官网的各种功能:包括登陆、注册、发送邮箱验证码、登陆验证码、页面登陆验证、发布文章、上传图片、form验证、点赞、评论、文章分页处理以及基于tronado的后端和ajax的前端数据处理。

    本博文将一步步带领你实现抽屉官网的各种功能:包括登陆.注册.发送邮箱验证码.登陆验证码.页面登陆验证.发布文章.上传图片.form验证.点赞.评论.文章分页处理以及基于tronado的后端和ajax的 ...

  5. 【MVC】ASP.NET MVC Forms验证机制

    http://www.cnblogs.com/bomo/p/3309766.html 随笔 - 121  文章 - 0  评论 - 92 [MVC]ASP.NET MVC Forms验证机制 ASP. ...

  6. Asp.Net MVC 身份验证-Forms

    Asp.Net MVC 身份验证-Forms 在MVC中对于需要登录才可以访问的页面,只需要在对应的Controller或Action上添加特性[Authorize]就可以限制非登录用户访问该页面.那 ...

  7. ajax实现用户登陆,退出,java做后端

    最近http老师布置了个任务,用cookie完成登陆,退出.Http老师讲的是node.js写后端,由于自己还是擅长java些,还是用Java做了. 以前跟着教程写过一个网站,当初是用jsp+serv ...

  8. MVC身份验证.MVC过滤器.MVC6关键字Task,Async.前端模拟表单验证,提交.自定义匿名集合.Edge导出到Excel.BootstrapTree树状菜单的全选和反选.bootstrap可搜索可多选可全选下拉框

    1.MVC身份验证. 有两种方式.一个是传统的所有控制器继承自定义Control,然后再里面用MVC的过滤器拦截.所以每次网站的后台被访问时.就会先走入拦截器.进行前端和后端的验证 一个是利用(MVC ...

  9. MVC用户验证

    MVC提供了四种Filter(钩子),用于在Action执行之前或者之后,我们能够做一些事情,比如说判断有没有登录,比如说判断有没有权限. IAuthorizationFilter:在所有Filter ...

随机推荐

  1. 基于 Java Web 的毕业设计选题管理平台--系统设计和任务分配

    一.团队作业:http://www.yzhiliao.com/course/70/task/440/show 二.个人作业: 1.项目的代码托管 (1).GitHub 地址:https://githu ...

  2. Beta版本冲刺(三)

    目录 组员情况 组员1(组长):胡绪佩 组员2:胡青元 组员3:庄卉 组员4:家灿 组员5:凯琳 组员6:翟丹丹 组员7:何家伟 组员8:政演 组员9:黄鸿杰 组员10:刘一好 组员11:何宇恒 展示 ...

  3. Alpha冲刺——day9

    Alpha冲刺--day9 作业链接 Alpha冲刺随笔集 github地址 团队成员 031602636 许舒玲(队长) 031602237 吴杰婷 031602220 雷博浩 031602634 ...

  4. C语言入门:05.scanf函数

    一.变量的内存分析 1.字节和地址 为了更好地理解变量在内存中的存储细节,先来认识一下内存中的“字节”和“地址”. (1)内存以“字节为单位”

  5. 深入 Nginx 之配置篇

     常用配置项 在工作中,我们与 Nginx 打交道更多的是通过其配置文件来进行.那么掌握这些配置项各自的作用就很有必要了. 首先,nginx.conf 的内容通常是这样的: ... ... #核心摸块 ...

  6. div文本垂直居中(div text vertical aligan)

    .box{ width: 135px;height: 84px;display: block; overflow: hidden; } .container { background:darkcyan ...

  7. 浅谈JavaSript中的this

    JavaScript的this对初学者来说一直是一个很头疼的问题,因为它的指向刚刚接触的时候往往觉得有点莫名奇妙,这篇博客用实例来概括一下,this代表什么以及如何改变函数的this. 在<Ja ...

  8. Python学习-------------------三级菜单简单版

    题目: 多级菜单         1.三级菜单         2.可依次选择进入的各子菜单         3.所需新知识点:列表.字典 ReadMe: 这个做循环,比较绕脑子 点开运行即可 Min ...

  9. MT【98】三元对称不等式

    评:这是一道浙江省省赛题,这里利用对称性,设$x\le y\le z$从而解决了问题.值得注意的是此处三元轮换对称正好也是完全对称,但如果变成一般的$n\ge4$元对称问题时,就不能设大小关系.事实上 ...

  10. 【刷题】BZOJ 1023 [SHOI2008]cactus仙人掌图

    Description 如果某个无向连通图的任意一条边至多只出现在一条简单回路(simple cycle)里,我们就称这张图为仙人掌图(cactus).所谓简单回路就是指在图上不重复经过任何一个顶点的 ...