Hola, estoy tratando de agregar un objeto a TempData
y redirigir a otra acción de controlador. Recibo el mensaje de error 500 cuando uso 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");
}
PD Lectura de posibles soluciones He agregado app.UseSession()
al método Configure
y services.AddServices()
en el método ConfigureServices
, pero fue en vano. ¿Hay alguna configuración oscura que debo tener en cuenta? ?
P.S agregando ConfigureServices
y UseSession
ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
services.AddDbContext<TreasureContext>(x=>x.UseMySql(connectionString:Constrings[3]));
services.AddMvc();
services.AddSession();
}
Configurar
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?}");
});
}
3 respuestas
Falta la línea services.AddMemoryCache();
en su método ConfigureServices (). Me gusta esto:
services.AddMemoryCache();
services.AddSession();
services.AddMvc();
Y después de eso, TempData debería funcionar como se esperaba.
Debe serializar el objeto antes de asignarlo a TempData ya que el núcleo solo admite cadenas y no objetos complejos.
TempData["UserData"] = JsonConvert.SerializeObject(searchedStory);
Y recuperar el objeto deserializándolo.
var story = JsonConvert.DeserializeObject<Story>(TempData["searchedStory"].ToString())
Agregue una extensión TempData como Session para serializar y deserializar
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);
}
}
Nuevas preguntas
c#
C # (pronunciado "see sharp") es un lenguaje de programación multi-paradigma de alto nivel, estáticamente tipado desarrollado por Microsoft. El código C # generalmente se dirige a la familia de herramientas y tiempos de ejecución .NET de Microsoft, que incluyen .NET Framework, .NET Core y Xamarin, entre otros. Use esta etiqueta para preguntas sobre el código escrito en las especificaciones formales de C # o C #.