Asp.net Core 过滤器(AuthorizationFilter,ActionFilter)

asp.net core 里面的过滤器有这么多(还提供的异步的过滤器):

IActionFilter

IResourceFilter

IResultFilter

IAuthorizationFilter

IPageFilter

IExceptionFilter

一、身份验证过滤器AuthorizationFilter

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

namespace CoreTest.Filter
{
    public class AuthFilter : Attribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            if (context.HttpContext.User.Identity.Name != "1") //只是个示范作用
            {
                //未通过验证则跳转到无权限提示页
                RedirectToActionResult content = new RedirectToActionResult("NoAuth", "Exception",null);
                context.Result = content;
            }
        }
    }
}

二、行为过滤器ActionFilter

using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZCommon;

namespace CoreTest.Filter
{
    public class OperationLogFilter : Attribute, IActionFilter
    {
        public OperationLogFilter(string operType)
        {
            this.OperType = operType;
        }
        public string Tag { get; set; }
        public string OperType { get; set; }
        /// 
        /// 执行前
        /// 
        /// 
        public void OnActionExecuting(ActionExecutingContext context)
        {
            LogHelper.WriteLog("参数:" + context.HttpContext.Request.Host, LogType.remark);
        }

        /// 
        /// 执行后
        /// 
        /// 
        public void OnActionExecuted(ActionExecutedContext context)
        {
        }

    }
}

 

你可能感兴趣的:(.net,Core)