使用HttpContext.SignInAsync实现简单的授权

1. 将认证添加到服务中

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                //登入地址
                options.LoginPath = "/Account/FcbLogin/";
                //登出地址
                options.LogoutPath = "/Account/FcbLogout/";
                //设置cookie过期时长
                //options.ExpireTimeSpan = TimeSpan.FromSeconds(10);
            });

所有CookieAuthenticationOptions 属性可以查看微软官方文档
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

2. 注入管道

这里认证要在授权之前注入

app.UseAuthentication();

3. 添加登入和登出

这里我没有验证用户账号密码,只是写了登入和登出的相关代码,这里也可以喝注入认证那里一样,这是票证过期时间

[HttpPost]
public async Task<ActionResult> Login(UserLogin model)
{
    //这里的scheme一定要和注入服务的scheme一样
    var identity = new ClaimsIdentity(new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme));
    //自定义的claim信息
    identity.AddClaim(new Claim("abc", "123"));
    AuthenticationProperties properties = new AuthenticationProperties()
    {
        //设置cookie票证的过期时间
        ExpiresUtc = DateTime.Now.AddDays(1),
        RedirectUri = model.ReturnUrl
    };
    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), properties);
 
    if (string.IsNullOrEmpty(model.ReturnUrl))
    {
        return LocalRedirect("/");
    }
    return LocalRedirect(model.ReturnUrl);
}  
[HttpGet]
public ActionResult FcbLoginOut()
{
    //AuthenticationProperties properties = new AuthenticationProperties()
    //{
    //    ExpiresUtc = DateTime.Now.AddDays(-100)
    //};
    HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
    return Ok();
}
<think> 根据用户要求,我将专注于HttpContext.Session的使用方法、示例和注意事项。参考提供的引用内容,特别是引用[2]和引用[4]中涉及Session的部分。 引用[2]展示了在类中使用HttpContext.Current.Session的示例代码,如: string username = HttpContext.Current.Session["username"].ToString(); 引用[4]则提到在一般处理程序(ashx)中使用Session时可能遇到的问题及解决方法。 因此,在回答中需要包含: 1. 如何在普通ASP.NET应用程序中使用HttpContext.Session(包括Web Forms、MVC等) 2. 在一般处理程序(.ashx)中使用Session的特殊处理 3. 注意事项(如空引用问题、线程安全等) 同时,根据系统指令,所有行内数学表达式用$...$,独立公式单独成段(但本问题可能不涉及数学公式),使用中文回答,并生成相关问题。 我将组织回答如下: - 首先介绍HttpContext.Session的基本用法 - 给出示例代码(包括普通场景和ashx场景) - 列举注意事项 - 最后生成相关问题 注意:引用标识要自然地添加在引用的内容末尾。 </think> ### C# HttpContext.Session 使用指南 #### 一、基本概念 HttpContext.Session 是 ASP.NET 提供的会话状态管理对象,用于存储用户特定的数据(如登录信息、购物车等),数据存储在服务器端并通过 Session ID 关联客户端。会话生命周期默认持续 20 分钟(可配置)[^2]。 #### 二、核心使用方法 1. **Session 数据存取** ```csharp // 存储数据 HttpContext.Current.Session["Username"] = "JohnDoe"; HttpContext.Current.Session["ShoppingCart"] = cartList; // 读取数据 string username = HttpContext.Current.Session["Username"]?.ToString(); List<CartItem> cart = HttpContext.Current.Session["ShoppingCart"] as List<CartItem>; ``` 2. **安全访问示例**(避免空引用) ```csharp // 推荐写法:空值检查 if (HttpContext.Current.Session["UserLevel"] != null) { int level = (int)HttpContext.Current.Session["UserLevel"]; } // 使用 TryGetValue 模式 var session = HttpContext.Current.Session; if (session.TryGetValue("LastLogin", out byte[] lastLoginBytes)) { DateTime lastLogin = Deserialize<DateTime>(lastLoginBytes); } ``` #### 三、特殊场景处理 1. **在一般处理程序 (.ashx) 中使用** ```csharp public void ProcessRequest(HttpContext context) { // 必须通过参数获取 Session context.Session["TempData"] = "ASHX_Session_Value"; // ❌ 错误用法:HttpContext.Current.Session 会导致空引用 } ``` *注意:在 ASHX 中需实现 `IRequiresSessionState` 接口启用 Session 支持[^4]。* 2. **异步环境中的线程安全** ```csharp lock (HttpContext.Current.Session.SyncRoot) { // 确保多线程操作的原子性 HttpContext.Current.Session["Counter"] = (int)Session["Counter"] + 1; } ``` #### 四、关键注意事项 1. **空引用问题** - 访问前需检查 `HttpContext.Current != null` - 使用 `?.` 运算符避免空引用异常[^2][^4] 2. **存储限制** - 默认每个会话存储 ≤ 1MB 数据 - 复杂对象需标记 `[Serializable]` 3. **生命周期** - 会话超时通过 `web.config` 配置: ```xml <system.web> <sessionState timeout="30"/> <!-- 分钟 --> </system.web> ``` 4. **性能优化** - 避免存储大型对象 - 禁用不需要会话的页面: ```csharp <%@ Page EnableSessionState="ReadOnly" %> ``` #### 五、跨平台场景 (.NET Core) 在 ASP.NET Core 中需显式启用会话服务: ```csharp // Startup.cs public void ConfigureServices(IServiceCollection services) { services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(30); }); } public void Configure(IApplicationBuilder app) { app.UseSession(); // 必须在 UseRouting 之后 } ``` 会话访问通过 `HttpContext.Session` 属性实现[^5]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值