Asp.net mvc验证用户登录之Forms实现详解
发布时间:2020-05-23 00:19:13 所属栏目: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-core – 在Microsoft.AspNet.Http.HttpContext中的
- 实体框架 – MVC 3 EF 4.1 dbContext – 删除具有不可空的外
- azure – 创建App Service订阅EMPTY
- asp.net-mvc – 为什么Visual Studio崩溃打开ASPX与MVC RC1
- asp.net-mvc – 存储库模式中的纯POCO实体更新问题
- asp.net会员提供者Guid userID
- asp.net-mvc-3 – 添加属性以选择列表选项
- asp.net中的页面卸载事件
- asp.net – IIS Express安装目录在哪里?
- asp.net-mvc-3 – MVC3 – 如何输出要下载的文件而不先将其
推荐文章
站长推荐
- ASP.NET成员:拒绝用户阻止CSS,页面无法正确呈现
- asp.net – 与WebAPI异步时保留HttpContext(中等
- asp.net – 优化的捆绑包在从网站请求时返回404
- asp.net – 考虑Scalablity和友好URL的GUID替代方
- asp.net-core – .NET Core的静态代码分析工具
- asp.net-mvc-4 – 后退点击刷新页面 – MVC 4
- 如何在ASP.Net Gridview中添加“确认删除”选项?
- asp.net – SQL – 两个不同长度的字符串之间的相
- asp.net – 哪些移动浏览器支持javascript(和Aja
- asp.net-mvc – ASP.Net MVC支持嵌套资源?
热点阅读
