c# – HttpContext.Current.Session始终为空
发布时间:2020-12-15 21:59:35 所属栏目:百科 来源:网络整理
导读:我知道这个话题已经出现了很多,但我找不到一个适用于我的问题的话题. 我有一个从ActionFilterAttribute派生的GuestTokenValidationAttribute类,在那里我从头部接收一个令牌,并将其用作String令牌.然后我想将该标记添加到会话中,但无论我做什么,Session始终为
我知道这个话题已经出现了很多,但我找不到一个适用于我的问题的话题.
我有一个从ActionFilterAttribute派生的GuestTokenValidationAttribute类,在那里我从头部接收一个令牌,并将其用作String令牌.然后我想将该标记添加到会话中,但无论我做什么,Session始终为null. 请各位指导或帮助,我们将不胜感激, 代码示例如下: public class GuestTokenValidationAttribute : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext actionContext) { string token; try { token = actionContext.Request.Headers.GetValues("Authorization-Token").First(); } catch (Exception) { actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized) { Content = new StringContent("Unauthorized User") }; return; } if(string.IsNullOrEmpty(token)) { actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized) { Content = new StringContent("Unauthorized User") }; return; } try { var repository = DependencyResolver.Current.GetService<IRepository<Guest>>(); var guest = repository.GetAll().FirstOrDefault(x => x.Token == token); if(guest == null) { actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized) { Content = new StringContent("Unauthorized User") }; return; } } catch (Exception) { actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized) { Content = new StringContent("Unauthorized User") }; return; } HttpContext.Current.Session.Add("guesttoken",token); base.OnActionExecuting(actionContext); } 解决方法
MVC移植到asp.net来解决Session和ViewState等问题,这是对网络性质的真正反对.如您所知,在MVC中,所有操作和响应都应被视为无状态请求,在处理请求之前和之后不应留下任何内容,并且假设GC将收集ViewBags,Session,Variables等中的所有数据.
因此,正如强烈推荐的那样,处理此类事物的常用方法是使用通过纯网络提供的本机设施,例如cookie,html-forms,html-inputs,url参数等. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |