ASP.NET Core Web

※This article is based on .NET 7

发送(Response)设置Cookie [edit]

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

[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");
}

进阶版 [edit]

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

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

依赖注入 [edit]

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

ASP.NET Core 中就内置了一个实现了该接口的 HttpContextAccessor 类

public class HttpContextAccessor : IHttpContextAccessor
{
    public HttpContextAccessor();
    public HttpContext HttpContext { get; set; }
}

为了实现依赖注入,需要将 IHttpContextAccessor 和 HttpContextAccessor 注入到 ServiceCollection 中,下面就用单例的模式进行注入

public void ConfigureServices(IServiceCollection services)
{
	services.AddSingleton<IHttpContextAccessor,HttpContextAccessor>();
	// 逻辑代码
}

写入 [edit]

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

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");
    }  
}

读取 [edit]

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

コメント:



(画像の文字列を入力して下さい)

トップ   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS