Asp.net mvc验证用户登录之Forms实现详解
发布时间:2021-01-12 05:49:04 所属栏目:asp.Net 来源:互联网
导读:这里我们采用asp.netmvc自带的AuthorizeAttribute过滤器验证用户的身份,也可以使用自定义过滤器,步骤都是一样。
这里我们采用asp.net mvc 自带的AuthorizeAttribute过滤器验证用户的身份,也可以使用自定义过滤器,步骤都是一样。 第一步:创建asp.net mvc项目, 在项目的App_Start文件夹下面有一个FilterConfig.cs,在这个文件中可以注册全局的过滤器。我们在文件中添加AuthorizeAttribute过滤器如下: public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); //将内置的权限过滤器添加到全局过滤中 filters.Add(new System.Web.Mvc.AuthorizeAttribute()); } } 第二步:在web.config配置文件中修改网站的身份认证为mode="Forms" <system.web> <!--Cockie名称,当用未登入时跳转的url--> <authentication mode="Forms"> <forms name="xCookie" loginUrl="~/Login/Index" protection="All" timeout="60" cookieless="UseCookies"></forms> </authentication> <compilation debug="true" targetFramework="4.5" /> <httpRuntime targetFramework="4.5" /> </system.web> 提示:配置name值作为最终生成的cookie的名称,loginUrl指定当用户未登入是跳转的页面,这里挑战到登入页面 第三步:添加用户登入相关的控制器和视图 创建LoginController控制器: public class LoginController : Controller { [HttpGet] [AllowAnonymous] public ActionResult Index() { return View(); } [HttpPost] [AllowAnonymous] public ActionResult Login(User user) { if (!user.Username.Trim().Equals("liuxin") || !user.Password.Trim().Equals("abc")) { ModelState.AddModelError("","用户名或密码错误"); return View("index",user); } //if (!user.Username.Trim().Equals("liuxin")) { // ModelState.AddModelError("Username","用户名错误"); // return View("index",user); / |
相关内容
- asp.net-mvc-4 – 在EF迁移配置类的Seed方法中获取App_Data
- 向.NET电子邮件添加附件
- ASP.NET VNext类库System.Runtime.Serialization
- ASP.NET性能优化之局部缓存分析
- asp.net-mvc – 使用自定义格式的ASP.NET MVC ViewModel映射
- .net – 加密ApplicationServices ConnectionString
- asp.net – axd和ashx处理程序之间的区别
- asp.net – 如何检查SQL Server代理是否正在运行
- asp.net – UserControl Viewstate在回发后丢失所有值
- Asp.Net的FileUpload类实现上传文件实例
推荐文章
站长推荐
热点阅读