Asp.NetCoreフィルタ(AuthorizationFilter,ActionFilter)

1935 ワード

asp.Netcoreの中のフィルタはこんなにたくさんあります(非同期のフィルタも提供されています):


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)
        {
        }

    }
}