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 );
        }
    }
  • 相关阅读:
    技术笔记3
    技术笔记2 jetty jboss
    技术笔记1前台
    日常笔记4
    日常笔记3
    日常笔记2
    日常笔记
    C语言——结构体
    用Java原子变量的CAS方法实现一个自旋锁
    Java中处理Linux信号量
  • 原文地址:https://www.cnblogs.com/netlock/p/14314237.html
Copyright © 2011-2022 走看看