Let's say we have code as follows:
public class HomeController : Controller
{
[HttpPost]
public IActionResult AdvanceTokenCallback(string apiToken)
{
Response.Cookies.Append("Token", apiToken, new Microsoft.AspNetCore.Http.CookieOptions()
{
Path = "/",
Expires = _tokenCookieExpirationTime
});
return RedirectToAction(nameof(CreateWorkItem));
}
[HttpGet]
public IActionResult CreateWorkItem()
{
string token = Request.Cookies["Token"];
return View();
}
}
When the action AdvanceTokenCallback
is called from external API the token
variable in the CreateWorkItem
action becomes a null
.
However in a case when I create a "bridge" action and move the logic which creates the cookie there, then the token
located in CreateWorkItem contains a value which is something that I expected.
public class HomeController : Controller
{
[HttpPost]
public IActionResult AdvanceTokenCallback(string apiToken)
{
return RedirectToAction(nameof(BridgeRedirect), new { apiToken });
}
[HttpGet]
public IActionResult BridgeRedirect(string apiToken)
{
Response.Cookies.Append("Token", apiToken, new Microsoft.AspNetCore.Http.CookieOptions()
{
Path = "/",
Expires = _tokenCookieExpirationTime
});
return RedirectToAction(nameof(CreateWorkItem));
}
[HttpGet]
public IActionResult CreateWorkItem()
{
string token = Request.Cookies["Token"];
return View();
}
}
Any idea why does it happen and is there a possibility to avoid having this extra BridgeRedirect
action with extra redirect?
I found that code works and do not on different machines and different environments when I run the app on localhost.
After I set the IsEssential
attribute to true when creating the Cookie everything works fine.
From the Microsoft documentation:
IsEssential - Indicates if this cookie is essential for the application to function correctly. If true then consent policy checks may be bypassed. The default value is false.
So the solution in my case is to just create a cookie like this:
Response.Cookies.Append("Token", apiToken, new Microsoft.AspNetCore.Http.CookieOptions()
{
IsEssential = true,
Expires = _tokenCookieExpirationTime
});
Using this way I don't need having this extra BridgeRedirect
anymore.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With