我有这种方法,我试图将请求重定向到另一个控制器。对于被叫控制器,我需要来自前一个控制器的一些数据,所以我把它放在了Tempdata中。但是当我在调用RedirectToAction的行之前使用Tempdata时,请求的内容根本没有传递给下一个动作
如下面的代码
public IActionResult GetAuthToken()
{
//Logic to generate AuthToken
//TODO:SRI 14/03/2017 Get the UserId from the front end app, For now I am hardcoding this value
AccountHolderDetails user = new AccountHolderDetails
{
UserId = "123",
FirstName = "",
LastName = "",
Email = "",
Phone = "",
Address = new UserAddress
{
Street = "123 anystreet",
City = "Brantford",
State = "ON",
Country = "CA"//,
//PostalCode = "M4P1E8"
}
};
var uniqueId = Guid.NewGuid();
var authToken = GenerateAuthToken(user.UserId, uniqueId);
var transactionRecord = CreateTransactionRecord(user,uniqueId,authToken);
// HttpContext.Session.Set("UserData", user);
TempData["UserData"] = user;
TempData["TransactionData"] = transactionRecord;
return RedirectToAction("Authorize", "Authorization");
}
我正在调用redirecttoaction之前设置Tempdata,当代码执行时,它不会通过授权控制器来授权方法。
我尝试在上面的代码中评论行的tempdata部分并且它工作正常,但我需要授权控制器中的用户数据,因此使用tempdata。我已按照核心网站的说明配置会话,所有这些都很好,如下所示,请查看我的starttup.cs课程
public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedMemoryCache();
services.AddSession(options => {
options.IdleTimeout = TimeSpan.FromSeconds(10);
options.CookieHttpOnly = true;
});
// Add framework services.
services.AddMvc();
services.Configure<WireCardSettings>(Configuration);
services.AddSingleton<ITempDataProvider, CookieTempDataProvider>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
答案 0 :(得分:2)
在将对象分配给TempData之前,必须先对其进行序列化。
TempData["UserData"] = JsonConvert.SerializeObject(user);
并通过反序列化来检索对象。
var user = JsonConvert.DeserializeObject<AccountHolderDetails>(TempData["UserData"].ToString());