前言:最近在倒腾 微软的新平台 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() { //逻辑代码 } }