Asp.net Core2.0 过滤器介绍

过滤器主要包含:授权过滤器、资源过滤器、Action过滤器、异常过滤器、结果过滤器。

(1)、授权过滤器 (Authorize):主要用于确定当前用户的请求是否合法。

  A、在 Startup.cs ConfigureServices方法中需要添加权限认证

public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();

            //添加权限认证
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(
                CookieAuthenticationDefaults.AuthenticationScheme, o =>
                {
                    o.LoginPath = new PathString("/Login/Index");
                });
        }

  B、在 Configure 方法中启动权限认证 app.UseAuthorization();

  C、在 Controller 调用;

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;

namespace WebApplication1.Controllers
{
    public class LoginController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Login()
        {
            var token = "abcdefg";
            var name = "幸福摩天轮";

            //以表单的形式
            ClaimsIdentity identity = new ClaimsIdentity("Forms");
            identity.AddClaim(new Claim(ClaimTypes.Sid, token));
            identity.AddClaim(new Claim(ClaimTypes.Name, name));

            ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(identity);

            //指定 Cookie 的名称
            HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,claimsPrincipal);

            return View();
        }

        [Authorize(AuthenticationSchemes=CookieAuthenticationDefaults.AuthenticationScheme)]
        public IActionResult Center()
        {
            //查看token
            var sid=User.FindFirstValue(ClaimTypes.Sid);

            //查看用户名称
            var name = User.FindFirstValue(ClaimTypes.Name);

            return Content(sid+name);
        }
    }
}

  D、实验截图

(2)、资源过滤器 (IResourceFilter):主授权之后的第一个用来处理请求的资源过滤器,也是最后一个接触到请求的过滤器。

  A、代码实现主要是继承 Attribute 和 IResourceFilter 

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

namespace WebApplication1.Filters
{
    public class ResoureFilter : Attribute, IResourceFilter
    {
        //在资源请求之后
        public void OnResourceExecuted(ResourceExecutedContext context)
        {
            throw new NotImplementedException();
        }

        //在资源请求之前
        public void OnResourceExecuting(ResourceExecutingContext context)
        {
            context.Result = new ContentResult() {Content="执行结束,资源请求失败!" };
        }
    }
}

  B、使用方式主要是在 IActionResult 上添加特性

     [ResoureFilter]
        public IActionResult Index()
        {
            return View();
        }

(3)、Action 过滤器 (IActionFilter):包装了对单个 action 方法的调用,可以将参数传递给 action 并从中获得 action result 。

  A、代码实现,主要是继承 IActionFilter 同时实现 OnActionExecuted 和 OnActionExecuting 方法

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

namespace WebApplication1.Filters
{
    public class ActionFilter : Attribute, IActionFilter
    {
        //在 Action 执行之后
        public void OnActionExecuted(ActionExecutedContext context)
        {
            throw new NotImplementedException();
        }

        //在 Action 执行之前
        public void OnActionExecuting(ActionExecutingContext context)
        {
            context.Result = new ContentResult() { Content = "执行结束,您没有请求该方法的权限!" };
        }
    }
}

  B、使用方式,主要是在 Action 上添加 ActionFilter 特性

        [ActionFilter]
        public IActionResult Index()
        {
            return View();
        }

(4)、异常过滤器 (ExceptionFilterAttribute):为 MVC 应用程序未处理异常应用全局策略。

  A、代码实现,主要是继承 IExcetionFilter 类,并且实现接口的方法。

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

namespace WebApplication1.Filters
{
    public class ExceptionFilter : Attribute, IExceptionFilter
    {
        public void OnException(ExceptionContext context)
        {
            context.Result = new ContentResult() { Content = "执行结束,系统发送错误!" };
        }
    }
}

  B、使用方式

        public IActionResult Index()
        {
            throw new System.Exception("系统发生故障");
        }

(5)、结果过滤器 (ResultFilterAttribute):包装了单个的 action result 的执行,并且仅当 action 方法成功执行完毕后方才运行。它们是理想的围绕视图执行或格式处理的逻辑。

原文地址:https://www.cnblogs.com/gzbit-zxx/p/13831656.html