ASP.NET Core MVC 过滤器简单使用

  1.token授权过滤器

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

namespace ModelFilter.Filter
{
    public class TokenHelper : IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationFilterContext filterContext)
        {
            string token = filterContext.HttpContext.Request.Headers["Authorization"];
            if (string.IsNullOrWhiteSpace(token))
            {

                filterContext.Result = new JsonResult(new { ReturnCode = 0, Message = "身份凭证已过期,请重新登录" });
                return;
            }

            if (token.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
            {
                token = token.Remove(0, 7);
            }
           // 获得token  进行简单验证
           // if ......
                      
        }
    }
}

 2.参数过滤器

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

namespace ModelFilter.Filter
{
    public class FilterHelper: ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!filterContext.ModelState.IsValid)
            {
                //获取验证失败的模型字段
                var errors = filterContext.ModelState
                    .Where(e => e.Value.Errors.Count > 0)
                    .Select(e => e.Value.Errors.First().ErrorMessage)
                    .ToList();

                var str = string.Join("|", errors);

                //设置返回内容
                var result = new
                {
                    returnCode = 0,
                    message = str
                };

                filterContext.Result = new JsonResult(result);
            }
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            
        }

        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
        }

        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
        }
    }
}

 3.异常过滤器

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

namespace ModelFilter.Filter
{
    public class ErrorHelper:IExceptionFilter
    {
        public void OnException(ExceptionContext context)
        {
            //throw new NotImplementedException();
            // 自定义返回内容
            var ret = new
            {
                returnCode = 0,
                message = context.Exception.Message
            };
            context.Result = new JsonResult(ret);
        }
    }
}

 4.Starup.cs配置方式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using ModelFilter.Filter;

namespace ModelFilter
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            // 关闭netcore自动处理参数校验默认机制
            services.Configure<ApiBehaviorOptions>((o) =>
            {
                o.SuppressModelStateInvalidFilter = true;
            });
            // 注入操作方法过滤器(全局注册)
            services.AddMvc(option => { option.Filters.Add<FilterHelper>(); });
            // 注入全局异常过滤器(全局注册)
            services.AddMvc(option => { option.Filters.Add<ErrorHelper>(); });
            // 注入授权过滤器(全局注册)
            services.AddMvc(option => { option.Filters.Add<TokenHelper>(); });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("Hello World!");
                });
                endpoints.MapControllers();
            });
        }
    }
}

 5.控制器方法和参数定义

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using ModelFilter.Filter;

namespace ModelFilter.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    public class HomeController : Controller
    {
        [HttpGet]
        public IActionResult GetIndex([FromQuery] User user)
        {
            throw new Exception("跑出一个错误");
        }
    }

    public class User{
        [Required(ErrorMessage = "{0}不能为空")]
        [StringLength(5, ErrorMessage = "最大长度不能超过 5")]
        public string Userid { get; set; }


        [Required(ErrorMessage = "用户年龄不能为空")]
        [Range(1, 100, ErrorMessage = "年龄必须介于1~100之间")]
        public int Code { get; set; }
    }
}

 

posted @ 2020-12-01 11:10  Besos  阅读(435)  评论(0编辑  收藏  举报