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

前言:最近在倒腾 微软的新平台 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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是ASP.NET Core MVC登录代码实现: 1. 在Startup.cs中添加身份验证和授权服务: ```csharp public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.LoginPath = "/Account/Login"; options.AccessDeniedPath = "/Account/AccessDenied"; }); services.AddAuthorization(options => { options.AddPolicy("AdminOnly", policy => policy.RequireRole("Admin")); }); // ... } ``` 2. 在AccountController.cs中添加登录和注销动作: ```csharp public class AccountController : Controller { private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; public AccountController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager) { _userManager = userManager; _signInManager = signInManager; } [HttpGet] public IActionResult Login(string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; return View(); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false); if (result.Succeeded) { return RedirectToLocal(returnUrl); } else { ModelState.AddModelError(string.Empty, "Invalid login attempt."); return View(model); } } return View(model); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Logout() { await _signInManager.SignOutAsync(); return RedirectToAction(nameof(HomeController.Index), "Home"); } private IActionResult RedirectToLocal(string returnUrl) { if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } else { return RedirectToAction(nameof(HomeController.Index), "Home"); } } } ``` 3. 在视图中添加登录表单: ```html @model LoginViewModel <form asp-controller="Account" asp-action="Login" asp-route-returnUrl="@ViewData["ReturnUrl"]" method="post" class="form-horizontal" role="form"> <div asp-validation-summary="All" class="text-danger"></div> <div class="form-group"> <label asp-for="Email" class="col-md-2 control-label"></label> <div class="col-md-10"> <input asp-for="Email" class="form-control" /> <span asp-validation-for="Email" class="text-danger"></span> </div> </div> <div class="form-group"> <label asp-for="Password" class="col-md-2 control-label"></label> <div class="col-md-10"> <input asp-for="Password" class="form-control" /> <span asp-validation-for="Password" class="text-danger"></span> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <div class="checkbox"> <label> <input asp-for="RememberMe" /> @Html.DisplayNameFor(m => m.RememberMe) </label> </div> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <button type="submit" class="btn btn-default">Log in</button> </div> </div> </form> ``` 这些代码将创建一个基本的登录和注销功能,用于保护应用程序中的受保护资源。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值