• 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 );
        }
    }
  • 相关阅读:
    [导入]C#播放rm文件[转贴]
    新工具软件发布!名称:剪切板记录器
    黑發4/14
    sql20002 4/19
    頁面按百分比設定失調3/27
    廣告控件:AdRotator 3/23
    19992020小農曆JS 3/31
    ASP.NET1.1編譯錯誤代碼:1073741502 4/10
    SiteMapPath控件 3/24
    MYSQL時間問題4/16
  • 原文地址:https://www.cnblogs.com/netlock/p/14314237.html
Copyright © 2020-2023  润新知