繁体   English   中英

在 .NET Core MVC 应用程序中使用 TempData 时出现错误 500

[英]Error 500 when using TempData in .NET Core MVC application

您好,我正在尝试向TempData添加一个对象并重定向到另一个控制器操作。 使用TempData时收到错误消息 500。

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");
}

PS通读可能的解决方案我已经加入app.UseSession()Configure方法和services.AddServices()ConfigureServices方法,但没有avail.Are有任何模糊的设置我必须知道的?

PS 添加ConfigureServicesUseSession

配置服务

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

配置

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?}");
            });
        }

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

TempData["UserData"] = JsonConvert.SerializeObject(searchedStory);

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

var story = JsonConvert.DeserializeObject<Story>(TempData["searchedStory"].ToString())

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

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

之后 TempData 应该按预期工作。

我正在研究 Dot net 5.0(目前处于预览阶段)。 就我而言,上述答案中提到的配置均无效。 TempData 导致 XHR 对象在 Dot net 5.0 MVC 应用程序中收到 500 内部服务器错误。 最后,我发现,缺少的部分是 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

添加 TempData 扩展,就像 Session 一样进行序列化和反序列化

    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);
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM