您的位置 首页 asp.Net

Asp.net mvc验证用户登录之Forms实现详解

这里我们采用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);
/

关于作者: dawei

【声明】:金华站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。

热门文章