.NET CookieContainer 是一个用于在 .NET 应用程序中存储和操作 Cookie 的容器类。它提供了一种简单的方式来存储和操作 Cookie,例如创建、读取、删除和过期 Cookie。
以下是 .NET CookieContainer 的一些优势:
以下是一个示例代码,演示如何使用 .NET CookieContainer:
using System.Collections.Generic;
using System.Net.Http;
using System.Web.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
namespace MyApp.Controllers
{
public class MyController : ApiController
{
private readonly MyAppOptions _options;
private readonly CookieContainer _cookieContainer = new CookieContainer();
public MyController(IOptions<MyAppOptions> options)
{
_options = options.Value;
}
[HttpPost]
public IHttpActionResult Login([FromBody] User user)
{
// Check if the user is authenticated
if (user == null || !_options.Authentication.IsEnabled())
{
return Unauthorized();
}
// Create a new cookie with the user's ID and expiration time
string userId = user.Id.ToString();
CookieOptions cookieOptions = new CookieOptions
{
HttpOnly = true,
Secure = _options.Authentication.IsSecure(),
Expires = DateTimeOffset.UtcNow.AddMinutes(30),
SameSite = SameSiteMode.Strict
};
_cookieContainer.Add(new Cookie(userId, null, cookieOptions));
// Return the user's ID and a success status code
return Ok(new { userId = userId });
}
[HttpGet]
public IHttpActionResult GetUser()
{
// Check if the user's cookie exists
if (_cookieContainer.Count == 0)
{
return Unauthorized();
}
// Return the user's ID and a success status code
string userId = _cookieContainer.GetCookieName();
return Ok(new { userId = userId });
}
[HttpDelete]
public IHttpActionResult Logout()
{
// Remove the user's cookie
_cookieContainer.DeleteCookie(null);
// Return a success status code
return Ok();
}
}
}
In this example, the MyController
class requires the MyAppOptions
class to be passed in as a dependency. This class is used to configure the authentication and security settings for the application. The CookieContainer
class is used to store the user's ID and authentication cookies. The HttpContextAccessor
class is used to access the current HTTP context and retrieve the authentication cookies.
领取专属 10元无门槛券
手把手带您无忧上云