Tuesday, August 1, 2023

ASP.NET Core - Create, Read and Delete Cookie

Project
  • Open the Visual Studio. 
  • Create web project using ASP.NET Core Empty template.
  • Project name: CookieCreateDeleteEtc
  • Solution name: CookieCreateDeleteEtc
  • .NET Core version: 5.0
  • Add the AddRazorPages() into the IServiceCollection in Startup class.
  • Use MapRazorPages() as terminal middleware in Startup class.
  • Add a new folder in project root folder and rename it Pages. 
  • Add a Razor Page in Pages folder and name it Index. 
Look at the below updated code in Startup class.
Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace CascadingDropdownsRP
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
            });
        }
    }
}
Update the Index.cshtml.
Index.cshtml

@page
@model CookieCreateDeleteEtc.Pages.IndexModel
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<style>
    .ck {
        font-size: 20px;
        color: blue;
        font-family: Impact;
    }
</style>
<div style="margin-left:30px;background-color:lightyellow;">
    <h1>Learn about cookies</h1>
    <label class="ck" style="color:red;">@ViewData["status"]</label><br /><br />
    <label class="ck" style="color:red;">@ViewData["info"]</label><br /><br />
    <a class="ck" asp-page-handler="Create">Create cookie</a><br />
    <a class="ck" asp-page-handler="Read">Read cookie</a><br />
    <a class="ck" asp-page-handler="Delete">Delete cookie</a><br />
</div>
Index.cshtml.cs
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System;

namespace CookieCreateDeleteEtc.Pages
{
    public class IndexModel : PageModel
    {
        private CookieOptions Cop
        {
            get
            {
                CookieOptions cop = new CookieOptions();
                cop.IsEssential = true;
                cop.MaxAge = TimeSpan.FromDays(2);
                cop.Expires = DateTime.Now.AddDays(1);
                cop.Path = "/";
                cop.Secure = true;
                cop.HttpOnly = true;
                cop.SameSite = SameSiteMode.None;
                return cop;
            }
        }
        public void OnGetCreate()
        {
            HttpContext.Response.Cookies.Append("mycookie", "cookie1", Cop);
            ViewData["status"] = "Cookie is created.";
            var cookieData = HttpContext.Response.Headers["Set-Cookie"].ToString();
            ViewData["info"] = cookieData;
        }
        public void OnGetRead()
        {
            var cuki = HttpContext.Request.Cookies["mycookie"];
            var status = string.IsNullOrEmpty(cuki) ? "missing." : cuki;
            //HttpContext.Request.Cookies.TryGetValue("mycookie", out string cuki2);
            ViewData["status"] = "Cookie is " + status;
            var cookieData = HttpContext.Response.Headers["Set-Cookie"].ToString();
            ViewData["info"] = cookieData;
        }
        public void OnGetDelete()
        {
            HttpContext.Response.Cookies.Delete("mycookie");
            ViewData["status"] = "Cookie is deleted.";
        }
    }
}
Result.

No comments:

Post a Comment

Hot Topics