Why is TempData coming back with no values

31 views Asked by At

We have a number of .Net 6 web apps where we use TempData and then use it in a view. We started on a new app and for some reason whenever I get to the view, any values I've set on the TempData are gone. I'm not doing any redirects, it's just a controller method where the base controller sets the values and then the controller renders the view. Here's the code. I've also tried ViewData and ViewBag, but nothing is working.

Base Controller

public class FWControllerBase : Controller
{
    protected FWModernViewModel baseViewModel;
    private TempDataDictionary TempData;
    
    public FWControllerBase(IFWSecurity FWSecurity, 
        IHttpContextAccessor contextAccessor,
        ITempDataProvider tempDataProvider)
    {
        if (!FWSecurity.ValidateUser())
            FWSecurity.Redirect();

        var _context = HttpContext ?? contextAccessor.HttpContext;
        var s = _context.Session;

        if (TempData == null) TempData = new TempDataDictionary(_context, tempDataProvider);
        
        baseViewModel = new FWModernViewModel()
        {
            UserName = s.GetData<string>(SessionVariables.UserName),
            IsRunningLocally = SiteConfigurationSettings.RunAgainstLocalDatabase,
            UserImageUrl = s.GetData<string>(SessionVariables.UserImageUrl),
            IsTheTerminator = s.GetData<bool>(SessionVariables.IsTheTerminator),
            Url = _context.Request.Path.ToString()
        };

        TempData["BaseViewModel"] = baseViewModel;
    }

    protected void SetTabType(Enums.Tab tab)
    {
        TempData[Enums.ViewDataKeys.ActiveTab.ToString()] = tab;
    }
}

Controller which inherits from the base

public class ThirdPartyTimesheetController : FWControllerBase
{
    private readonly IThirdPartyTimesheetImportService _thirdPartyTimesheetImportService;
    public ThirdPartyTimesheetController(IFWSecurity FWSecurity, 
        IHttpContextAccessor contextAccessor,
        ITempDataProvider tempDataProvider, 
        IThirdPartyTimesheetImportService thirdPartyTimesheetImportService) : 
        base(FWSecurity, contextAccessor, tempDataProvider)
    {
        _thirdPartyTimesheetImportService = thirdPartyTimesheetImportService;
        base.SetTabType(Enums.Tab.Accounting);
    }

    public async Task<ActionResult> Index()
    {
        var timesheets = await _thirdPartyTimesheetImportService.GetTimesheetsNeedingProcessed();
        return View(timesheets);
    }
}

and then in the layout view

@{
    var viewModel = new FWModernViewModel();
    var tab = Enums.Tab.Home;
    
    if (TempData.Keys.Count > 0) //this always comes back as 0
    {
        if (TempData[Enums.ViewDataKeys.ActiveTab.ToString()] != null)
            tab = (Enums.Tab) TempData[Enums.ViewDataKeys.ActiveTab.ToString()];
        
        if (TempData["BaseViewModel"] != null)
            viewModel = TempData["BaseViewModel"] as FWModernViewModel;
    }
}

and our startup file

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllersWithViews()
    .AddSessionStateTempDataProvider()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.PropertyNamingPolicy = null;
    });

builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders =
        ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});

builder.Services.Configure<IISServerOptions>(options =>
{
    options.AllowSynchronousIO = true;
});

builder.Services.AddSystemWebAdapters();
builder.Services.AddHttpForwarder();

// Add services to the container.
builder.Services.AddDistributedSqlServerCache(options =>
{
    options.ConnectionString = DataSources.SessionStateSource;
    options.SchemaName = DataSources.SessionStateDefaultSchema;
    options.TableName = DataSources.FWSessionsTable;
});

builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromHours(5);
    options.Cookie.Name = "FW.Session";
    options.Cookie.IsEssential = true;
});

builder.Services.AddRazorPages();

var mvcBuilder = builder.Services.AddControllersWithViews();
#if DEBUG
mvcBuilder.AddRazorRuntimeCompilation();
#endif

builder.Services.AddHttpContextAccessor();

SiteConfigurationSettings.LoadConfiguration(builder.Configuration);

builder.Services.RegisterServices(new FWRegistrySpec());
builder.Services.InitializeAutoMapper();

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseHsts();
}

app.UseForwardedHeaders();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions()
{
    FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot"))
});

app.UseSession();

app.Use(async (context, next) => {
    context.Request.EnableBuffering();
    await next();
});

var emailNotifier = app.Services.GetService<IEmailNotifier>();
app.UseMiddleware<ErrorHandlingMiddleware>(emailNotifier, app.Environment.ApplicationName);

app.UseRouting();
app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Login}/{action=Index}/{id?}");

    endpoints.MapRazorPages();
});

app.UseSystemWebAdapters();
app.MapDefaultControllerRoute();
app.MapForwarder("/{**catch-all}", app.Configuration["ProxyTo"]).Add(static builder => ((RouteEndpointBuilder)builder).Order = int.MaxValue);

var scope = app.Services.CreateScope();
var manager = scope.ServiceProvider.GetService<IRabbitMQManager>();
var subscribers = scope.ServiceProvider.GetServices<IEventSubscriber>();
var tasks = subscribers.Select(p => p.SubscribeToEvents());

Task.Run(() => manager.SubscribeAll(tasks)).Wait();

app.Run();
0

There are 0 answers