#author("2023-11-16T17:03:58+08:00","default:Admin","Admin")
#author("2023-11-17T10:09:51+08:00","default:Admin","Admin")
[[ASP.NET Core Web]]

&color(red){※This article is based on .NET 7};

#contents

* 发送(Response)设置Cookie [#v90ceebe]

发送带有Set-Cookie标头的响应
现在,我们已经完成了设置Cookie的准备工作,接下来我们可以在控制器的某个方法中发送带有Set-Cookie标头的响应。以下是一个示例:


#codeprettify{{
[HttpGet]
public IActionResult SetCookie()
{
    var cookieOptions = new CookieOptions
    {
        Secure = true,
        SameSite = SameSiteMode.None,
        Expires = DateTime.Now.AddDays(1)
    };

    //添加Cookie
    Response.Cookies.Append("token", "your_token_value", cookieOptions);
    //删除某个Cookie
    Response.Cookies.Delete(somekey);

    return Ok("Cookie set successfully");
}
}}


* 进阶版 [#k9f6840f]
[[参考这里的调用代码>+.NetCore+HttpContext#k9f6840f]]

不直接使用父类 Controller 的 Request 和 HttpContext,这是因为此方式是一种强依赖,接下来给大家演示如何通过依赖注入的方式获取 HttpContext,此种更加灵活。

在 ASP.NET Core 中要想得到 cookie 必须要有 Request 对象,要想得到 Request 对象 必须要有 HttpContext,要想得到 HttpContext 必须要利用 IHttpContextAccessor 接口

** 依赖注入 [#p3c9741a]

#codeprettify{{
public interface IHttpContextAccessor
{
    HttpContext HttpContext { get; set; }
}
}}

ASP.NET Core 中就内置了一个实现了该接口的 HttpContextAccessor 类
#codeprettify{{
public class HttpContextAccessor : IHttpContextAccessor
{
    public HttpContextAccessor();
    public HttpContext HttpContext { get; set; }
}
}}

为了实现依赖注入,需要将 IHttpContextAccessor 和 HttpContextAccessor 注入到 ServiceCollection 中,下面就用单例的模式进行注入
#codeprettify{{
public void ConfigureServices(IServiceCollection services)
{
	services.AddSingleton<IHttpContextAccessor,HttpContextAccessor>();
	// 逻辑代码
}
}}

** 写入 [#ceb1e433]

然后就可以通过依赖注入的方式获取 IHttpContextAccessor 接口的实例,再依次获取 HttpContext 对象,下面的代码片段展示了如何在 Controller 中访问 IHttpContextAccessor 实例

#codeprettify{{
public class HomeController : Controller
{
    private readonly IHttpContextAccessor _httpContextAccessor;
    public HomeController(IHttpContextAccessor httpContextAccessor)
    {
        this._httpContextAccessor = httpContextAccessor;
    }   

    //写入Cookie
    public IActionResult Write(string key, string value, bool isPersistent)
    {
    	CookieOptions options = new CookieOptions();
    	if (isPersistent)
    		options.Expires = DateTime.Now.AddDays(1);
    	else
    		options.Expires = DateTime.Now.AddSeconds(10);
    	_httpContextAccessor.HttpContext.Response.Cookies.Append(key, value, options);
    	return View("WriteCookie");
    }  
}
}}
** 读取 [#cac81576]

#codeprettify{{
public IActionResult Read(string key)
{
	ViewBag.Data = _httpContextAccessor.HttpContext.Request.Cookies[key];
	return View("ReadCookie");
}
}}    


#hr();
コメント:
#comment_kcaptcha

トップ   編集 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS