asp.net core 2.0 登录验证(不包含登录过程)
时间:2019-08-19 04:48:29 +0800 CST 浏览:3489

控制器验证

重写Controller方法

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCo…

控制器验证

重写Controller方法

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Routing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MvcMovie.Filters
{
    public class AuthenticationControllor : Controller
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.HttpContext.Session.GetString("_Name") == null)
            {
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Home", action = "Index", test = "hello" }));
            }

            base.OnActionExecuting(filterContext);
        }
    }
}

使用方法

    public class HelloWorldController : AuthenticationControllor
    {
        // GET: /HelloWorld/   
        public ActionResult Index()
        {
            return View();
        }
    }

过滤器特性验证

定义过滤器特性

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Routing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MvcMovie.Filters
{
    // 登录认证特性
    public class AuthenticationAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.HttpContext.Session.GetString("_Name") == null)
            {

                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Home", action = "Index", test = "hello" }));

            }

            base.OnActionExecuting(filterContext);
        }
    }
}

使用方法

        [Authentication]
        public IActionResult Contact()
        {
            ViewData["Message"] = "Your contact page.";

            return View();
        }

附加说明

设置session

HttpContext.Session.SetString("_Name", "bing");

读取session

HttpContext.Session.GetString("_Name");


如果这篇文章对你有所帮助,可以通过下边的“打赏”功能进行小额的打赏。

本网站部分内容来源于互联网,如有侵犯版权请来信告知,我们将立即处理。


来说两句吧