asp.net core自定义授权过滤器

1.记录点击页面的地址,如果点击页面时未登录,直接跳转到登录页面,登录后直接跳转到自己点击的页面
2.创建授权过滤器

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Web;

namespace Log4NetTest
{
    //授权过滤器
    public class CustomerAuthorizeAttribute : Attribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            //获取目前地址
            var controller = context.RouteData.Values["controller"];
            var action = context.RouteData.Values["action"];
            //判断是否登录
            if (!context.HttpContext.User.Identity!.IsAuthenticated)
            {
                //记录要跳转的页面路径
                context.Result = new
                RedirectToActionResult("Login", "WeatherForecast",
                new { RedirectUrl = HttpUtility.UrlEncode($"/{controller}/{action}") });
            }
        }
    }
}

2.登录接口

[HttpPost]
        public async Task<IActionResult> Login(string usename, string pwd, string RedirectUrl)
        {
            var user = await _userManager.FindByNameAsync(usename);
            if (user != null)
            {
                var re = await _signInManager.PasswordSignInAsync(user, pwd, false, false);
                if (re.Succeeded)
                {
                    if (!string.IsNullOrEmpty(RedirectUrl))
                    {
                        //进行页面跳转
                        return Redirect(HttpUtility.HtmlDecode(RedirectUrl));
                    }
                    return Ok();
                }
                return Ok();
            }
            return Ok();
        }

你可能感兴趣的:(asp.net,后端)