【问题标题】:Error 500 when using TempData in .NET Core MVC application在 .NET Core MVC 应用程序中使用 TempData 时出现错误 500
【发布时间】:2018-07-02 17:18:24
【问题描述】:

您好,我正在尝试将对象添加到 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");
}

P.S 通读可能的解决方案我已将 app.UseSession() 添加到 Configure 方法和 services.AddServices()ConfigureServices 方法中但无济于事。是否有任何我必须注意的晦涩设置?

P.S 添加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?}");
            });
        }

【问题讨论】:

  • 请发布您的 Startup.ConfigureServices 和 Startup.Configure 方法。
  • 我已经发过了。
  • 从不只是一个错误 500,没有任何错误消息。查看您的日志,了解实际错误 是什么。如果您找不到解决方案,请确保在您的问题中包含完整的错误消息。
  • 请务必阅读how to use TempData correctly...

标签: c# asp.net-core tempdata


【解决方案1】:

您必须先序列化对象,然后再将其分配给 TempData,因为核心仅支持字符串而不支持复杂对象。

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

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

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

【讨论】:

  • 这是我的问题,它让我发疯。使用复杂对象导致我返回 500 错误,没有任何异常或解释任何它返回 500。序列化它是要走的路。
  • 完美运行。感谢您拯救这一天:D
【解决方案2】:

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

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

然后 TempData 应该按预期工作。

【讨论】:

  • Asp.net Core 3 用户须知 此解决方案不适用于您,请参阅 Agrawal Shraddha 解决方案。
  • @MohammedA.Fadil 这个解决方案将在 Mvc Core 3 应用程序中工作。评论前请先研究一下。
  • 我进行了研究,您的解决方案对我不起作用。经过反复试验,Agrawal Shraddha 解决方案在 3.1 上完美地为我工作
  • 恕我直言,我提供的解决方案可以在我的 MVC.NET Core 3 应用程序中正常使用。:) 可以这么说,“此解决方案不适用于 Asp.net Core 3 个用户”有点牵强,因为我正在开发的应用程序与您的陈述相矛盾。编程愉快!:)
  • @MohammedA.Fadil 我可以确认,这不适用于 Core 3.1。
【解决方案3】:

我正在开发 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

【讨论】:

    【解决方案4】:

    像 Session 一样添加一个 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);
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-22
      • 2021-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多