Error 500 when using TempData in .NET Core MVC application

时间:2018-01-23 19:22:54

标签: c# asp.net-core tempdata

Hello i am trying to add an object to TempData and redirect to another controller-action. I get error message 500 when using TempData.

public IActionResult Attach(long Id)
{
    Story searchedStory=this.context.Stories.Find(Id);
    if(searchedStory!=null)
    {
        TempData["tStory"]=searchedStory;  //JsonConvert.SerializeObject(searchedStory) gets no error and passes 

        return RedirectToAction("Index","Location");
    }
    return View("Index");
}


public IActionResult Index(object _story) 
{             
    Story story=TempData["tStory"] as Story;
    if(story !=null)
    {
    List<Location> Locations = this.context.Locations.ToList();
    ViewBag._story =JsonConvert.SerializeObject(story);
    ViewBag.rstory=story;
    return View(context.Locations);
    }
    return RedirectToAction("Index","Story");
}

P.S Reading through possible solutions I have added app.UseSession() to the Configure method and services.AddServices() in the ConfigureServices method but to no avail.Are there any obscure settings i must be aware of?

P.S adding ConfigureServices and UseSession

ConfigureServices

 public void ConfigureServices(IServiceCollection services)
            {
                services.AddOptions();
                services.AddDbContext<TreasureContext>(x=>x.UseMySql(connectionString:Constrings[3]));
                services.AddMvc();
                services.AddSession();
            }

Configure

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();
            app.UseSession();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }

4 个答案:

答案 0 :(得分:4)

在将对象作为核心支持字符串而不是复杂对象分配给TempData之前,必须序列化该对象。

TempData [“UserData”] = JsonConvert.SerializeObject(searchingStory);

并通过反序列化来检索对象。

var story = JsonConvert.DeserializeObject(TempData [“searchingStory”]。ToString())

答案 1 :(得分:2)

您的ConfigureServices()方法中缺少services.AddMemoryCache();行。像这样:

        services.AddMemoryCache();
        services.AddSession();
        services.AddMvc();

之后,TempData应该按预期工作。

答案 2 :(得分:2)

我正在使用Dot net 5.0(目前处于预览状态)。就我而言,以上答案中提到的所有配置均无效。 TempData导致XHR对象在Dot net 5.0 MVC应用程序中收到500 Internal server error。最后,我发现缺少的部分是AddSessionStateTempDataProvider()

`public void ConfigureServices(IServiceCollection services)
        {
            services.AddBrowserDetection();
            services.AddDistributedMemoryCache();

            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromSeconds(120);
            });

            services.AddControllersWithViews().
                .AddSessionStateTempDataProvider();
        }`

使用TempData时添加会话非常重要,因为TempData在内部使用Session变量来存储数据。在这里,@ Agrawal Shraddha的回答也非常有效。 Asp.Net Core / Dot net 5.0不支持TempData直接存储复杂对象。相反,它必须序列化为Json字符串,并且在检索它时需要再次反序列化。

`TempData[DATA] = JsonConvert.SerializeObject(dataObject);`

和Configure()方法如下:

`public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseSession();

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

有关TempData配置设置的更多信息,要使其正常工作,请参阅以下文章: https://www.learnrazorpages.com/razor-pages/tempdata

答案 3 :(得分:1)

像添加Sesssion一样添加TempData扩展以进行序列化和反序列化

    public static class TempDataExtensions
    {
        public static void Set<T>(this ITempDataDictionary tempData, string key, T value)
        {
           string json = JsonConvert.SerializeObject(value);
           tempData.Add(key, json);
        }

        public static T Get<T>(this ITempDataDictionary tempData, string key)
        {
            if (!tempData.ContainsKey(key)) return default(T);

            var value = tempData[key] as string;

            return value == null ? default(T) :JsonConvert.DeserializeObject<T>(value);
        }
    }