zoukankan      html  css  js  c++  java
  • NET 5 过滤器给控制器传值

    1.方法一 (HttpContext.Items)

     获取

     

    中间件

    public class MySuperAmazingMiddleware
    {
        private readonly RequestDelegate _next;
    
        public MySuperAmazingMiddleware(RequestDelegate next)
        {
            _next = next;
        }
    
        public Task Invoke(HttpContext context)
        {
            var mySuperAmazingObject = GetSuperAmazingObject();
    
            context.Items.Add("SuperAmazingObject", mySuperAmazingObject );
    
            // Call the next delegate/middleware in the pipeline
            return this._next(context);
        }
    }

    获取

    var mySuperAmazingObject = (SuperAmazingObject)HttpContext.Items["mySuperAmazingObject"];

    2.方法二 (HttpContext.User)

    public class SampleActionFilter : IAsyncActionFilter
    {
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var claimsIdentity = new ClaimsIdentity(new Claim[] {
                new Claim(ClaimTypes.Name, "test") }, "Basic");
            var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
            context.HttpContext.User = claimsPrincipal;
            await next();
        }
    }
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc(options =>
        {
            options.Filters.Add<SampleActionFilter>();
        });
    }
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return Content("Current User: " + User.Identity.Name );
        }
    }
  • 相关阅读:
    JavaScript
    多线程
    MySQL进阶一(基础查询)
    英语语法随笔1
    MySQL
    Love Story
    两个数组的交集
    只出现一次的数字
    MybatisPlus
    数组中值加一
  • 原文地址:https://www.cnblogs.com/netlock/p/14314237.html
Copyright © 2011-2022 走看看