Logo

Logo

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

Pastore Antonio
Pastore Antonio 2022年05月19日
1266 阅读 0 评论 约 4002 字 阅读约 9 分钟

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);
        }
    }
}

 

查看完整代码

橙子主题打折出售

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

购买它

附件下载

共 2 个文件
20181127102721970
PNG 4.3 KB
20181127102925180
PNG 4.7 KB
部分文章可能存在转载,如果涉及到侵权,请联系删除文章。

探索AIGC相关的精彩内容,共 15 篇文章

Azure AI 服务之语音识别

简介 Azure AI 服务中的语音识别 API 是微软提供的一项先进技术,旨在帮助开发者轻松实现语 ... ASP.NET MVC使用Authorize过滤器验证用户登录

2026-02-17 · Xzavier Aaron
MCP | 一文详解什么是 MCP以及 MCP 可以做什么

一、什么是 MCP MCP(Model Context Protocol)是一个专为大型语言模型(L ... ASP.NET MVC使用Authorize过滤器验证用户登录

2026-02-14 · Shen, Luke
你的工作流程,值得一个“全自动数字分身”:录制、截图、成文,一气呵成

一、一句话认识 TestFlow Recorder 在数字化工作环境中,如何准确记录操作步骤并生成清 ... ASP.NET MVC使用Authorize过滤器验证用户登录

2026-02-14 · Xzavier Aaron
Flowise 前端框架配置指南

用户需求 问题:有没有适合配置 Flowise 的前端框架? 目标:寻找类似 Open WebUI ... ASP.NET MVC使用Authorize过滤器验证用户登录

2026-02-14 · Xzavier Aaron