小编Hem*_*rya的帖子

在Asp.Net Core中使用TempData时无法重定向到操作

我试图在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);
    }
Run Code Online (Sandbox Code Playgroud)

起初我假设TempData默认工作,但后来意识到必须添加和配置它.我在启动时添加了ITempDataProvider.官方文件似乎描述了这应该足够了.它没用.然后我还将它配置为使用Session

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

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

app.UseSession();
Run Code Online (Sandbox Code Playgroud)

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

.net asp.net asp.net-core-mvc asp.net-core asp.net-core-1.1

4
推荐指数
1
解决办法
2407
查看次数