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。

相关内容

热门资讯

详情透视!wepoker的辅助... 详情透视!wepoker的辅助器,微乐小程序辅助器脚本,方式教程(有挂猫腻)-哔哩哔哩1、首先打开w...
详细透视!fishpoker透... 详细透视!fishpoker透视底牌!本来有辅助工具(确实有挂)-哔哩哔哩1、fishpoker透视...
专业透视!竞技联盟破解版最新版... 专业透视!竞技联盟破解版最新版,微信小程序微乐挂如何获取,法门教程(竟然有挂)-哔哩哔哩1、起透看视...
分享透视!约局吧能不能开挂!切... 分享透视!约局吧能不能开挂!切实真的有辅助攻略(确实有挂)-哔哩哔哩1、超多福利:超高返利,海量正版...
分享透视!hhpoker是正规... 分享透视!hhpoker是正规的吗,微乐自建房辅助神器怎么安装,资料教程(的确有挂)-哔哩哔哩1、下...
教你透视!pokemmo内置修... 教你透视!pokemmo内置修改器!一贯是有辅助脚本(发现有挂)-哔哩哔哩1、pokemmo内置修改...
揭幕透视!哈糖大菠萝免费辅助器... 揭幕透视!哈糖大菠萝免费辅助器,微乐小程序卡五星脚本,积累教程(有挂解惑)-哔哩哔哩1、完成哈糖大菠...
详细透视!xpoker辅助助手... 详细透视!xpoker辅助助手!本来一直总是有辅助教程(有挂细节)-哔哩哔哩1、点击下载安装,xpo...
关于透视!约局吧怎么看有没有挂... 关于透视!约局吧怎么看有没有挂,微信小程序游戏充值破解,方式教程(有挂秘诀)-哔哩哔哩在进入约局吧怎...
详情透视!红龙poker作必弊... 详情透视!红龙poker作必弊指令!原来是真的有辅助教程(有人有挂)-哔哩哔哩1.红龙poker作必...