Asp.net mvc验证用户登录之Forms实现详解
发布时间:2021-01-12 09:49:57 所属栏目: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 – ASP.NET MVC3中的随机会话超时
- asp.net-mvc – ASP.NET MVC中的代码
- asp.net-mvc – 在Controller操作方法中重用代码
- asp.net-mvc-2 – 在名称中使用连字符处理MVC2变
- ASP.NET 清除模式窗口数据缓存的操作方式
- asp.net中mvc使用ajax提交参数的匹配问题解决探讨
- asp.net-mvc – MVC错误 – 传入字典的模型项目的
- asp.net-core – 使用IdentityServer4生成访问令
- asp.net-mvc – LabelFor和TextBoxFor不生成相同
- asp.net-mvc – MVC“添加控制器”是“无法检索元
热点阅读
