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

标签 c# asp.net-core tempdata

你好,我正在尝试将对象添加到 TempData 并重定向到另一个 Controller 操作。我在使用 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?}");
            });
        }

最佳答案

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

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

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

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

关于c# - 在 .NET Core MVC 应用程序中使用 TempData 时出现错误 500,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48409313/

相关文章:

asp.net-mvc - 在 ASP.NET MVC 中使用 Tempdata - 最佳实践

c# - AzureWebjobSDK 中的 StorageConnectionString 是否需要访问整个存储帐户?

asp.net-core - 在部署槽交换后,如何优雅地迁移打开的 Websocket 连接?

visual-studio - 如何使用.NET Core类库(.NET Standard)连接SQL Server数据库?

c# - Entity Framework Core 单个对象而不是列表

asp.net-mvc - ASP.NET MVC CookieTempDataProvider.DeserializeTempData 返回 null

asp.net-mvc - 表单发布后如何在我的 View 中检查 TempData 值?

c# - 将批处理文件输出重定向到 winform 文本框问题

javascript - 使用 Jquery 在 asp.net GridView 中查找所有复选框

c# - MongoDb 的 C# 驱动程序,是否可以将其包装在通用 session 中?