asp.net5.0webapi项目中在中间件中访问TempData。
创始人
2024-09-17 03:30:18
0
  1. 在Startup.cs的Configure方法中注册TempData:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseRouting();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
    app.UseSession();  // 添加支持session
    app.Use(async (context, next) =>
    {
        context.RequestServices.GetRequiredService().SetSession(context.Session);
        await next.Invoke();
    });
    app.Use(async (context, next) =>
    {
        var tempData = context.RequestServices.GetService().GetTempData(context);
        context.Items["TempData"] = tempData;  // 保存到上下文中,以便后续中间件使用
        await next.Invoke();
    });  
}
  1. 使用中间件读取TempData:
public class MyMiddleware
{
    private readonly RequestDelegate _next;
    
    public MyMiddleware(RequestDelegate next)
    {
        _next = next;
    }
    
    public async Task InvokeAsync(HttpContext context)
    {
        var tempData = context.Items["TempData"] as ITempDataDictionary;
        if (tempData != null)
        {
            tempData["key"] = "value";  // 设置TempData值
        }
        
        await _next(context);
    }
}
  1. 注册中间件:
app.UseMiddleware();

注意:必须在Session中间件之后注册TempData中间件,否则可能无法正常使用TempData。

相关内容

热门资讯

辅助透视!德普之星的辅助工具介... 辅助透视!德普之星的辅助工具介绍,wpk辅助哪里买,学习教程(真实有挂)-哔哩哔哩一、德普之星的辅助...
辅助透视!pokemmo辅助工... 辅助透视!pokemmo辅助工具!总是一直都是有辅助技巧(有挂技巧)-哔哩哔哩1、每一步都需要思考,...
教你透视!wepoker私人局... 教你透视!wepoker私人局有透视吗,wepoker破解版内购,手册教程(有挂规律)-哔哩哔哩1、...
揭幕透视!大菠萝免费辅助器!总... 揭幕透视!大菠萝免费辅助器!总是是真的有辅助攻略(有挂总结)-哔哩哔哩1、点击下载安装,大菠萝免费辅...
揭露透视!wepoker透视挂... 揭露透视!wepoker透视挂底牌,wepoker买钻石有用吗,模块教程(有挂规律)-哔哩哔哩一、w...
关于透视!pokemmo辅助器... 关于透视!pokemmo辅助器手机版下载!本来真的是有辅助工具(确实有挂)-哔哩哔哩小薇(辅助器软件...
辅助透视!wepoker怎么提... 辅助透视!wepoker怎么提高运气,pokemmo脚本,举措教程(有挂教学)-哔哩哔哩1)wepo...
揭幕透视!拱趴大菠萝万能挂图解... 揭幕透视!拱趴大菠萝万能挂图解!原来真的是有辅助软件(有挂工具)-哔哩哔哩1、拱趴大菠萝万能挂图解辅...
教你透视!pokemmo脚本,... 教你透视!pokemmo脚本,德普之星有辅助软件吗,课程教程(有挂透明挂)-哔哩哔哩1、下载好德普之...
有挂透视!大菠萝手游辅助!都是... 有挂透视!大菠萝手游辅助!都是真的是有辅助工具(有挂头条)-哔哩哔哩1、操作简单,无需大菠萝手游辅助...