ASP NET Core 3 1 State Management With Cookies - Part 12
This is part 12 of the current playlist on ASP.NET Core 3.1 lecture videos. In this part, we walk through creating an ASP.NET Core 3.1 MVC application from scratch to show how the cookies are persisting data in between the trip to the server and back and how the cookies can be deleted by calling an appropriate method on the cookie object. Cookies are one of several methods employed in State Management in ASP.Net Core 3.1
#aspnetcore31 #cookies #statemanagement #aspnetcore31mvc
#cookieauthentication
Code: (HomeController.cs)
public class HomeController : Controller
{
public IActionResult Index()
{
string Name = Request.Cookies["Name"];
return View("Index", Name);
}
[HttpPost]
public IActionResult Index(IFormCollection form)
{
string Name = form["Name"].ToString();
CookieOptions options = new CookieOptions();
options.Expires = DateTime.Now.AddMinutes(10);
Response.Cookies.Append("Name", Name, options);
return RedirectToAction(nameof(Index));
}
public IActionResult DeleteCookie()
{
Response.Cookies.Delete("Name");
return View("Index");
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
View(Index.cshtml)
@model string
@{
ViewData["Title"] = "Home Page";
}
@if (!string.IsNullOrWhiteSpace(Model))
{
<div>Welcome back, @Model</div>
@Html.ActionLink("Forget Me", "DeleteCookie")
}
else
{
<form asp-action="Index">
<span> It is your visit to the site. Welcome to My Site !!</span><br />
<label> Please put your Name:</label>
@Html.TextBox("Name")
<div class="form-group">
<input type="submit" value="Update" class="btn btn-primary" />
</div>
</form>
Comments
Post a Comment