Logo

ASP.NET MVC使用Authorize过滤器验证用户登录

photo

2022年05月19日

ASP.NET MVC使用Authorize过滤器验证用户登录。Authorize过滤器首先运行在任何其它过滤器或动作方法之前,主要用来做登录验证或者权限验证。

示例:使用Authorize过滤器实现简单的用户登录验证。

1、创建登录控制器LoginController

/// <summary>
/// 登录控制器
/// </summary>
[AllowAnonymous]
public class LoginController : Controller
{
    /// <summary>
    /// 登录页面
    /// </summary>
    public ActionResult Index()
    {
        return View();
    }

    /// <summary>
    /// 登录
    /// </summary>
    [HttpPost]
    public ActionResult Login(string loginName, string loginPwd)
    {
        if (loginName == "admin" && loginPwd == "123456")
        {
            //登录成功
            Session["LoginName"] = loginName;
            return RedirectToAction("Index", "Home");
        }
        else
        {
            //登录失败
            return RedirectToAction("Index", "Login");
        }
    }

    /// <summary>
    /// 注销
    /// </summary>
    public ActionResult Logout()
    {
        Session.Abandon();
        return RedirectToAction("Index", "Login");
    }
}

注意:在登录控制器LoginController上添加AllowAnonymous特性,该特性用于标记在授权期间要跳过AuthorizeAttribute的控制器和操作。

2、创建登录页面

@{
    ViewBag.Title = "登录页面";
    Layout = null;
}

<h2>登录页面</h2>

<form action='@Url.Action("Login","Login")' id="form1" method="post">
    用户:<input type="text" name="loginName" /><br />
    密码:<input type="password" name="loginPwd" /><br />
    <input type="submit" value="登录">
</form>

效果图:

3、创建主页控制器LoginController

public class HomeController : Controller
{
    public ActionResult Index()
    {
        //获取当前登录用户
        string loginName = Session["LoginName"].ToString();
        ViewBag.Message = "当前登录用户:" + loginName;
        return View();
    }
}

 4、创建主页页面

@{
    ViewBag.Title = "Index";
    Layout = null;
}

<h2>Index</h2>
<h3>@ViewBag.Message</h3>
<a href="@Url.Action("Logout","Login")">注销</a>

效果图:

5、创建授权过滤器LoginAuthorizeAttribute类

创建Filter目录,在该目录下创建授权过滤器LoginAuthorizeAttribute类,继承AuthorizeAttribute。

using System.Web.Mvc;

namespace MvcApp.Filter
{
    /// <summary>
    /// 授权过滤器
    /// </summary>
    public class LoginAuthorizeAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            //判断是否跳过授权过滤器
            if (filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)
               || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
            {
                return;
            }

            //判断登录情况
            if (filterContext.HttpContext.Session["LoginName"] == null || filterContext.HttpContext.Session["LoginName"].ToString()=="")
            {
                //HttpContext.Current.Response.Write("认证不通过");
                //HttpContext.Current.Response.End();

                filterContext.Result = new RedirectResult("/Login/Index");
            }
        }
    }
}

通常Authorize过滤器也是在全局过滤器上面的,在App_Start目录下的FilterConfig类的RegisterGlobalFilters方法中添加:

using System.Web;
using System.Web.Mvc;
using MvcApp.Filter;

namespace MvcApp
{
    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());

            //添加全局授权过滤器
            filters.Add(new LoginAuthorizeAttribute());
        }
    }
}

Global.asax下的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace MvcApp
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}

 

橙子主题打折出售

其实我不卖,主要是这里是放广告的,所以就放了一个
毕竟主题都没做完,卖了也是坑.

购买它
本文为原创文章,请注意保留出处!
log4net-mvc中引用log4net 2022年05月19日

引用包点击需要添加log4net项目,在线下载安装包,如下:在管理器中输入log4net下载一个...log4net-mvc中引用log4net

热门文章

WordPress 后台编辑器样式实现直接预览 在WordPress3.0以后,有一个新的实用功能:你可以更改默认后台编辑器(TinyMCE)的样...WordPress后台编辑器样式实现直接预览 作者:Pastore Antonio
1451 浏览量
【干货】Chrome插件(扩展)开发全攻略 写在前面我花了将近一个多月的时间断断续续写下这篇博文,并精心写下完整demo,写博客的辛苦大家懂的...【干货】Chrome插件(扩展)开发全攻略 作者:Pastore Antonio
1417 浏览量
CentOS 编译错误+配置错误解决方法集合 ERROR:theHTTPXSLTmodulerequiresthelibxml2/l...CentOS编译错误+配置错误解决方法集合 作者:Pastore Antonio
1410 浏览量
WordPress中加载JavaScript脚本的方法 在WordPress中加载脚本(为CSS和JS,下同)文件,大多数人的做法是直接在hea...WordPress中加载JavaScript脚本的方法 作者:Pastore Antonio
1386 浏览量
wordpress学习五: 通过wordpress_xmlrpc的python包远程操作wordpress wordpress提供了丰富的xmlrpc接口api来供我们远程操控wp的内容。伟大的开源社区有人就...wordpress学习五:通过wordpress_xmlrpc的python包远程操作wordpress 作者:Pastore Antonio
1384 浏览量