Google Code Prettify

ASP.NET Core Razer page 中要如何設定 Cookie 安全使用? 及如何保存及移除Cookie?

在 ASP.NET Core Razor Pages 中,設置 Cookie 安全使用、保存 Cookie 和移除 Cookie 與在 MVC 中的操作類似。以下是如何在 Razor Pages 中實現這些功能的詳細步驟。


設定 Cookie 安全使用
首先,確保你在 Startup.cs 中配置了 Cookie 的安全性設置。


Startup.cs 中的配置

public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();

    services.ConfigureApplicationCookie(options =>
    {
        options.Cookie.HttpOnly = true;
        options.Cookie.SecurePolicy = CookieSecurePolicy.Always; // 僅在 HTTPS 上傳輸
        options.Cookie.SameSite = SameSiteMode.Strict; // 嚴格的 SameSite 策略
        options.Cookie.Name = "YourCookieName";
        options.ExpireTimeSpan = TimeSpan.FromMinutes(60); // 設置過期時間
        options.SlidingExpiration = true; // 滑動過期時間
    });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();

    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
    });
}



保存 Cookie
在 Razor Pages 中,你可以在 Page Model 中使用 HttpContext.Response.Cookies.Append 方法來保存 Cookie。

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System;

public class SetCookieModel : PageModel
{
    public IActionResult OnGet()
    {
        var cookieOptions = new CookieOptions
        {
            HttpOnly = true,
            Secure = true,
            SameSite = SameSiteMode.Strict,
            Expires = DateTimeOffset.UtcNow.AddMinutes(60) // 設置過期時間
        };

        Response.Cookies.Append("YourCookieName", "YourCookieValue", cookieOptions);

        return Page();
    }
}



移除 Cookie
你可以使用 HttpContext.Response.Cookies.Delete 方法來移除 Cookie。

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.RazorPages;

public class RemoveCookieModel : PageModel
{
    public IActionResult OnGet()
    {
        Response.Cookies.Delete("YourCookieName");
        return Page();
    }
}



讀取 Cookie
你可以使用 HttpContext.Request.Cookies 來讀取 Cookie 的值。

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.RazorPages;

public class ReadCookieModel : PageModel
{
    public string CookieValue { get; private set; }

    public IActionResult OnGet()
    {
        if (Request.Cookies.TryGetValue("YourCookieName", out string cookieValue))
        {
            CookieValue = cookieValue;
        }
        else
        {
            CookieValue = "Cookie not found.";
        }

        return Page();
    }
}


完整範例
以下是一個完整的 Razor Pages 範例,包含設置、讀取和刪除 Cookie 的操作。

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();

    services.ConfigureApplicationCookie(options =>
    {
        options.Cookie.HttpOnly = true;
        options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
        options.Cookie.SameSite = SameSiteMode.Strict;
        options.Cookie.Name = "YourCookieName";
        options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
        options.SlidingExpiration = true;
    });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();

    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
    });
}


SetCookie.cshtml.cs

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System;

public class SetCookieModel : PageModel
{
    public IActionResult OnGet()
    {
        var cookieOptions = new CookieOptions
        {
            HttpOnly = true,
            Secure = true,
            SameSite = SameSiteMode.Strict,
            Expires = DateTimeOffset.UtcNow.AddMinutes(60)
        };

        Response.Cookies.Append("YourCookieName", "YourCookieValue", cookieOptions);

        return Page();
    }
}



RemoveCookie.cshtml.cs

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

public class RemoveCookieModel : PageModel
{
    public IActionResult OnGet()
    {
        Response.Cookies.Delete("YourCookieName");
        return Page();
    }
}


ReadCookie.cshtml.cs

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

public class ReadCookieModel : PageModel
{
    public string CookieValue { get; private set; }

    public IActionResult OnGet()
    {
        if (Request.Cookies.TryGetValue("YourCookieName", out string cookieValue))
        {
            CookieValue = cookieValue;
        }
        else
        {
            CookieValue = "Cookie not found.";
        }

        return Page();
    }
}


結論
這些步驟展示了如何在 ASP.NET Core Razor Pages 中設置 Cookie 的安全性、保存 Cookie 和移除 Cookie。通過正確的配置和操作,可以確保 Cookie 的安全使用。