【问题标题】:Not able to redirect to action when using TempData in Asp.Net Core在 Asp.Net Core 中使用 TempData 时无法重定向到操作
【发布时间】:2017-03-23 13:56:37
【问题描述】:

我试图在 Asp.Net Core 中实现一个简单的事情。这在 Asp.Net Mvc 中没什么大不了的。我有这样的动作方法

public async Task<IActionResult> Create([Bind("Id,FirstName,LastName,Email,PhoneNo")] Customer customer)
    {
        if (ModelState.IsValid)
        {
            _context.Add(customer);
            await _context.SaveChangesAsync();
            TempData["CustomerDetails"] = customer;
            return RedirectToAction("Registered");
        }
        return View(customer);
    }

public IActionResult Registered()
    {
        Customer customer = (Customer)TempData["CustomerDetails"];
        return View(customer);
    }

起初我认为 TempData 默认工作,但后来意识到必须添加和配置它。我在启动时添加了 ITempDataProvider。官方文档好像描述这样应该就够了。它没有用。然后我也将它配置为使用 Session

public void ConfigureServices(IServiceCollection services)
{
      services.AddMemoryCache();
      services.AddSession(
            options => options.IdleTimeout= TimeSpan.FromMinutes(30)
            );
      services.AddMvc();
      services.AddSingleton<ITempDataProvider,CookieTempDataProvider>();
}

在编写 app.UseMvc 之前,我在 Startup 的 Configure 方法中与 Session 相关的以下行。

app.UseSession();

这仍然不起作用。发生的事情是我没有因为使用 TempData 而出现任何异常,我之前错过了一些配置,但现在创建操作方法无法重定向到注册方法。 Create 方法完成所有工作,但 RedirectToAction 无效。如果我删除将客户详细信息分配给 TempData 的行,则 RedirectToAction 会成功重定向到该操作方法。但是在这种情况下,注册操作方法显然无法访问 CustomerDetails。我错过了什么?

【问题讨论】:

  • 您可以尝试使用 JSON 序列化和反序列化 - TempData["CustomerDetails"] = JsonConvert.SerializeObject(customer);var customer = JsonConvert.DeserializeObject&lt;Customer&gt;((TempData["CustomerDetails"] ?? "").ToString()); 吗?
  • 好吧。我使用的是服务器端 TempData 而不是 cookie。我认为我们不需要为此目的序列化为 JSON。
  • 显然我们都知道。由于我们看不到 Customer 类中的内容,我想看看 TempData 是否不起作用或数据本身是否无效,无法序列化为 TempData。

标签: asp.net .net asp.net-core asp.net-core-mvc asp.net-core-1.1


【解决方案1】:

@Win。你是对的。在阅读本文的免责声明后,我意识到了序列化,只要你想在 Asp.net Core 中使用 TempData,就需要反序列化。

https://andrewlock.net/post-redirect-get-using-tempdata-in-asp-net-core/

我首先尝试使用 BinaryFormatter,但发现它也已从 .NET Core 中删除。然后我使用NewtonSoft.Json进行序列化和反序列化。

TempData["CustomerDetails"] = JsonConvert.SerializeObject(customer);

public IActionResult Registered()
    {
        Customer customer = JsonConvert.DeserializeObject<Customer>(TempData["CustomerDetails"].ToString());
        return View(customer);
    }

这是我们现在必须做的额外工作,但现在看起来就是这样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-05
    • 1970-01-01
    • 2021-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多