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安装绝活儿!wepoke... WPK安装绝活儿!wepoker免费脚本咨询,德州微扑克其实真的是有开挂技巧1、wepoker免费脚...
WPK多开技法!德朴之星脚本,... WPK多开技法!德朴之星脚本,德州微扑克一贯存在有辅助教程1、这是跨平台的德朴之星脚本轻量版有透视,...
WPK有透视手册!wepoke... WPK有透视手册!wepoker透视脚本网页,德州微扑克本来真的是有开挂app1、超多福利:超高返利...
WPK私人局演示!wepoke... WPK私人局演示!wepoker辅助透视软件,德州微扑克总是真的有辅助appwepoker辅助透视软...
WPK靠谱策略!wepoker... WPK靠谱策略!wepokerplus开挂,德州微扑克真是真的有开挂教程1、在wepokerplus...
WPK透视版要领!wepoke... WPK透视版要领!wepoker新号好一点吗,德州微扑克切实存在有透视教程wepoker新号好一点吗...
WPK控制牌策略!wepoke... WPK控制牌策略!wepoker透视脚本免费下载,德州微扑克本来存在有辅助攻略wepoker透视脚本...
WPK插件演示!wepoker... WPK插件演示!wepoker网页版透视方法,德州微扑克好像真的有开挂神器1)wepoker网页版透...
WPK作弊窍要!wejoker... WPK作弊窍要!wejoker辅助脚本,德州微扑克好像存在有透视appwejoker辅助脚本辅助器是...
WPK靠谱练习!wepoker... WPK靠谱练习!wepoker透视有用吗,德州微扑克一直存在有辅助教程1、操作简单,无需wepoke...