This is how I am setting my cookie in my controller. When I navigate to the About function, I get this error:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
Microsoft.AspNetCore.Http.IRequestCookieCollection.this[string].get returned null
Is this the correct way to set a cookie after I login or authenticate my user? .
public IActionResult Index()
{
LoginViewModel lvm = new LoginViewModel
{
Email = "login@app.com",
Password = "Password"
};
var result = authenticationClient.Authenticate(lvm);
Response.Cookies.Append("Token", result.Token);
Response.Cookies.Append("RefreshToken", result.RefreshToken);
return View();
}
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
ViewBag.Message = GetCookieValueFromResponse(Response, "Token");
return View();
}
Also, is it possible to create a reusable generic class to set a cookie and read it?
This is not a duplicate just because it has a null exception. I have tried this method to retrieve my cookie but it just returns null?
string GetCookieValueFromResponse(HttpResponse response, string cookieName)
{
foreach (var headers in response.Headers)
{
if (headers.Key != "Set-Cookie")
continue;
string header = headers.Value;
if (header.StartsWith($"{cookieName}="))
{
var p1 = header.IndexOf('=');
var p2 = header.IndexOf(';');
return header.Substring(p1 + 1, p2 - p1 - 1);
}
}
return null;
}