您的位置:首页 > 编程语言 > ASP

asp.net Core 2.0 MVC为Controller或Action添加定制特性实现登录验证

2020-02-29 18:58 591 查看

前言:最近在倒腾 微软的新平台 asp.net Core 2.0,在这个过程中有些东西还是存在差异。下面是我在学习过程的一点笔记。有不妥之处,望各位大虾指正!

 

一、先创建一个控制器继承于Controller的BaseController,代码如下:

using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Zen.Core.Models;
using Zen.Core.Comm;
using Microsoft.AspNetCore.Mvc.Controllers;

namespace Zen.Web.Controllers
{
public class BaseController : Controller
{
public override void OnActionExecuting(ActionExecutingContext context)
{
base.OnActionExecuting(context);
bool result = false;

var attrib = (context.ActionDescriptor as ControllerActionDescriptor).MethodInfo.
               GetCustomAttributes(typeof(CheckLogin), false).FirstOrDefault(); var attr = attrib as CheckLogin; if (attr != null) { if (attr.IsNeedLogin) { result = true; } else { result = false; } } if (!IsLogin() && result) { //如果没有登录,则跳至登陆页 context.Result = Redirect("GoogleApiBase/Login"); } } protected bool IsLogin() { Administrator adminobj = HttpContext.Session.GetObjectFromJson<Administrator>("admin"); //获取登录session if (adminobj != null) return true; return false; } } }

 

二、再创建一个验证类CheckLogin,代码如下:

using System;

namespace Zen.Web.Controllers
{
public sealed class CheckLogin : Attribute
{
public bool IsNeedLogin = false;

public CheckLogin(bool isNeed)
{
this.IsNeedLogin = isNeed;
}
}
}

 

三、开始应用,代码如下:

public class TestController : BaseController
{
[CheckLogin(false)]
public IActionResult Index()
{
//逻辑代码
}
}

 

转载于:https://www.cnblogs.com/CHNMurphy/p/7527494.html

  • 点赞
  • 收藏
  • 分享
  • 文章举报
aeh30444 发布了0 篇原创文章 20000 · 获赞 0 · 访问量 79 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐