TempData error in asp.net core

I am trying to use TempData in the asp.net core. However, I get a null value in the get TempData method. Can someone please let me know how I can use TempData in asp.net core

Listed below are the things I added during the study.

Project.json File

{ "dependencies": { "Microsoft.NETCore.App": { "version": "1.0.1", "type": "platform" }, "Microsoft.AspNetCore.Mvc": "1.0.1", "Microsoft.AspNetCore.Routing": "1.0.1", "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0", "Microsoft.AspNetCore.Server.Kestrel": "1.0.1", "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0", "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0", "Microsoft.Extensions.Configuration.Json": "1.0.0", "Microsoft.Extensions.Logging": "1.1.0", "Microsoft.Extensions.Logging.Console": "1.0.0", "Microsoft.Extensions.Logging.Debug": "1.0.0", "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0", "Microsoft.EntityFrameworkCore.SqlServer": "1.1.0", "Microsoft.EntityFrameworkCore.Tools": "1.1.0-preview4-final", "Microsoft.EntityFrameworkCore.Design": "1.1.0", "Microsoft.EntityFrameworkCore.SqlServer.Design": "1.1.0", "DataBase": "1.0.0-*", "UnitOfWork": "1.0.0-*", "ViewModel": "1.0.0-*", "Common": "1.0.0-*", "System.IdentityModel.Tokens.Jwt": "5.0.0", "Microsoft.AspNetCore.Authentication.JwtBearer": "1.0.0", "Microsoft.AspNetCore.Diagnostics": "1.0.0", "Microsoft.AspNetCore.StaticFiles": "1.0.0", "Microsoft.AspNetCore.Session": "1.1.0", "Microsoft.Extensions.Caching.Memory": "1.1.0" }, "tools": { "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final", "Microsoft.EntityFrameworkCore.Tools.DotNet": "1.0.0-preview3-final", "Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final" }, "frameworks": { "netcoreapp1.0": { "imports": [ "dotnet5.6", "portable-net45+win8" ] } }, "buildOptions": { "emitEntryPoint": true, "preserveCompilationContext": true }, "runtimeOptions": { "configProperties": { "System.GC.Server": true } }, "publishOptions": { "include": [ "wwwroot", "**/*.cshtml", "appsettings.json", "web.config" ] }, "scripts": { "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ] } } 

start.cs file

 public void ConfigureServices(IServiceCollection services) { services.AddMemoryCache(); services.AddSession(); // Add framework services. services.AddMvc(); services.AddTransient<IMarketUOW, MarketUow>(); services.AddTransient<ICategoryUow, CategoryUow>(); services.AddTransient<IUserProfileUow, UserProfileUow>(); services.AddTransient<IItemUow, ItemUow>(); services.AddTransient(typeof(IGenericRepository<>), typeof(GenericRepository<>)); var connection = Configuration.GetConnectionString("DefaultConnection"); services.AddDbContext<EmakitiContext>(options => options.UseSqlServer(connection)); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseSession(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } 

Here is the implementation of tempdata.When this method is called, I can see the value in TempData.

 [HttpGet("{pageNumber}")] public GenericResponseObject<List<MarketViewModel>> GetMarketList(int pageNumber) { TempData["Currentpage"] = pageNumber; TempData.Keep("Currentpage"); GenericResponseObject<List<MarketViewModel>> genericResponseObject = new GenericResponseObject<List<MarketViewModel>>(); genericResponseObject.IsSuccess = false; genericResponseObject.Message = ConstaintStingValue.Tag_ConnectionFailed; try { var marketItem = _iMarketUow.GetMarketList(pageNumber); genericResponseObject.Data = marketItem.Item1; var totalPages = (int)Math.Ceiling((decimal)marketItem.Item2 / (decimal)10); genericResponseObject.TotalPage = totalPages; genericResponseObject.IsSuccess = true; genericResponseObject.Message = ConstaintStingValue.Tag_SuccessMessageRecord; genericResponseObject.Message = ConstaintStingValue.Tag_ConnectionSuccess; } catch (Exception exception) { genericResponseObject.IsSuccess = false; genericResponseObject.Message = exception.Message; genericResponseObject.ErrorCode = exception.HResult; genericResponseObject.ExceptionErrorMessage = exception.StackTrace; } return genericResponseObject; } 

But the method below has a null value in temp data.

 [HttpPost] public GenericResponseObject<List<MarketViewModel>> AddUpdateMarket([FromBody] MarketViewModel marketViewModel) { GenericResponseObject<List<MarketViewModel>> genericResponseObject = new GenericResponseObject<List<MarketViewModel>>(); genericResponseObject.IsSuccess = false; genericResponseObject.Message = ConstaintStingValue.Tag_ConnectionFailed; if (marketViewModel!= null && ModelState.IsValid) { try { _iMarketUow.AddUpdateMarketList(marketViewModel); genericResponseObject = GetMarketList(Convert.ToInt16(TempData.Peek("Currentpage"))); } catch (Exception exception) { genericResponseObject.IsSuccess = false; genericResponseObject.Message = exception.Message; genericResponseObject.ErrorCode = exception.HResult; genericResponseObject.ExceptionErrorMessage = exception.StackTrace; } } else { genericResponseObject.Message = ConstaintStingValue.Tag_InputDataFormatNotMatch; } return genericResponseObject; } 

Here is a debug session image

first http request that contains a value for tempdata

null for the second request

+19
c # asp.net-mvc asp.net-web-api asp.net-core
source share
2 answers

After switching to ASP Core 2.1, I had this problem, and after one day of work, I found a solution:

in Startup.Configure () app.UseCookiePolicy(); should be after app.UseMVC();

+32
source share

Update all packages to the same version 1.1.0 , and also add caching. Here are the essentials for using TempData in Asp.Net Core

Project.json

 "Microsoft.AspNetCore.Session": "1.1.0" 

Here is the Startup.cs file. - ConfigureServices Method

 public void ConfigureServices(IServiceCollection services) { services.AddMemoryCache(); services.AddSession(); services.AddMvc(); } 

And set up the method.

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseSession(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } 

Now try with TempData , it will work.

And you can set the environment with the ASPNETCORE_ENVIRONMENT = development environment variable set.

PS

ASP.NET Core MVC provides the TempData property on the Controller . TempData can be used to store temporary data that should be available for only one request after the current request.

When an object in TempDataDictionary is read, it will be marked for deletion at the end of this request.

The Peek and Keep methods allow you to read a value without marking it for deletion. Say we go back to the first query where the value was stored in TempData .

With Peek you get the value without marking it for deletion with a single call.

 //second request, PEEK value so it is not deleted at the end of the request object value = TempData.Peek("value"); //third request, read value and mark it for deletion object value = TempData["value"]; 

With Keep you specify the key that was marked for deletion that you want to keep. Retrieving an object and then saving it when deleted are two different calls.

 //second request, get value marking it from deletion object value = TempData["value"]; //later on decide to keep it TempData.Keep("value"); //third request, read value and mark it for deletion object value = TempData["value"]; 
+14
source share

All Articles