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();
});
}
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);
}
}
app.UseMiddleware();
注意:必须在Session中间件之后注册TempData中间件,否则可能无法正常使用TempData。