2021年4月8日星期四

Asp.Net Core TempData attribute - value is always null

I'm using the [TempData] attribute on a property of my Controller class, e.g:

public class FooController : Controller  {      [TempData]      public string ReturnUrl { get; set; }          ....  }  

And setting this value in an Index action handling a GET request:

public IActionResult Index(string returnUrl = null)  {      this.ReturnUrl = returnUrl;        // Do stuff...        return View();  }  

I have a second action handling a POST request which is raised from the first (Index) action, it's here that I need to read the TempData value back:

[HttpPost]  public IActionResult HandlePost(int id)  {      // Do post things...        // Read value from [TempData] backed property      string returnUrl = this.ReturnUrl;            return this.Redirect(returnUrl);  }  

However I'm finding that the value of the ReturnUrl property is always null.

But if I use TempData directly like this:

// Set return url  TempData["returnUrl"] = returnUrl;  

And

// Get return url  string returnUrl = TempData["returnUrl"] as string;  

It works fine - am I using the attribute incorrectly? Is it possible to use [TempData] in this way?

https://stackoverflow.com/questions/67007372/asp-net-core-tempdata-attribute-value-is-always-null April 08, 2021 at 11:38PM

没有评论:

发表评论