GVKun编程网logo

c# – HttpContext.Current.Session为null(c#的session)

15

在本文中,您将会了解到关于c#–HttpContext.Current.Session为null的新资讯,同时我们还将为您解释c#的session的相关在本文中,我们将带你探索c#–HttpConte

在本文中,您将会了解到关于c# – HttpContext.Current.Session为null的新资讯,同时我们还将为您解释c#的session的相关在本文中,我们将带你探索c# – HttpContext.Current.Session为null的奥秘,分析c#的session的特点,并给出一些关于.net HttpContext.Current.Request.RawUrl、.net – 为什么HttpContext.Current.Handler为null?、ajax – 设置HttpContext.Current.User、Asp.net System.Web.HttpContext.Current.Session null in global.asax的实用技巧。

本文目录一览:

c# – HttpContext.Current.Session为null(c#的session)

c# – HttpContext.Current.Session为null(c#的session)

我有一个WebSite与一个类库中的一个自定义Cache对象.所有的项目都在运行.NET 3.5.
我想将此类转换为使用Session状态而不是缓存,以便在应用程序回收时保留stateerver中的状态.
但是,当我访问我的Global.asax文件中的方法时,这个代码会引发异常“HttpContext.Current.Session is null”.我打电话给这个类:
Customer customer = CustomerCache.Instance.GetCustomer(authTicket.UserData);

为什么对象allways空?

public class CustomerCache: System.Web.SessionState.IRequiresSessionState
{
    private static CustomerCache m_instance;

    private static Cache m_cache = HttpContext.Current.Cache;

    private CustomerCache()
    {
    }

    public static CustomerCache Instance
    {
        get
        {
            if ( m_instance == null )
                m_instance = new CustomerCache();

            return m_instance;
        }
    }

    public void AddCustomer( string key,Customer customer )
    {
        HttpContext.Current.Session[key] = customer;

        m_cache.Insert( key,customer,null,Cache.NoAbsoluteExpiration,new TimeSpan( 0,20,0 ),CacheItemPriority.NotRemovable,null );
    }

    public Customer GetCustomer( string key )
    {
        object test = HttpContext.Current.Session[ key ];

        return m_cache[ key ] as Customer;
    }
}

你可以看到我已经尝试添加IRequiresSessionState到类,但没有什么不同.

干杯

解决方法

这不是真的关于将国家纳入你的班级,而是在你的Global.asax中你所说的.会话不可用于所有方法.

一个工作的例子是:

using System.Web.SessionState;

// ...

protected void Application_PreRequestHandlerExecute(object sender,EventArgs e)
    {
        if (Context.Handler is IRequiresSessionState || Context.Handler is IReadOnlySessionState)
        {
            HttpContext context = HttpContext.Current;
            // Your Methods
        }
    }

它不会工作,例如在Application_Start中

.net HttpContext.Current.Request.RawUrl

.net HttpContext.Current.Request.RawUrl

.net  HttpContext.Current.Request.RawUrl   获取当前请求的原始URL  是什么意思
什么是原始URL,取得的值是什么,在JAVA中该如何实现 请指教

.net – 为什么HttpContext.Current.Handler为null?

.net – 为什么HttpContext.Current.Handler为null?

我正在尝试访问HttpModule中的一个页面,我想我应该通过调用HttpContext.Current.Handler(这应该引用当前页面)来做到这一点,但我一直都是null.

我正在使用.Net 3.5框架开发.

我在AuthorizeRequest和AuthenticateRequest上检查这个

谢谢.

解决方法

可能,请求尚未发送给处理程序(例如,您在BeginRequest中).

ajax – 设置HttpContext.Current.User

ajax – 设置HttpContext.Current.User

我正在开发一个asp.net mvc 3.0应用程序,它具有简单的身份验证过程.用户填写一个表单,该表单通过ajax调用发送到服务器并获得响应,但这里的问题是使用以下方法:
FormsAuthentication.SetAuthCookie(person.LoginName,false);

是不足以填充’HttpContext.Current.User’,它需要运行以下方法:

FormsAuthentication.RedirectFromLoginPage("...");

问题在于,正如我所提到的,loggin表单使用ajax表单,并使用json获取响应,因此无法重定向.

我怎么能填写’HttpContext.Current.User’?

谢谢.

更新:

这是注册方法:

[HttpPost]
        public ActionResult Register(Person person)
        {
            var q = da.Persons.Where(x => x.LoginName == person.LoginName.ToLower()).FirstOrDefault();

            if (q != null)
            {
                ModelState.AddModelError("","Username is repettive,try other one");

                return Json(new object[] { false,this.RenderPartialViewToString("RegisterControl",person) });
            }
            else
            {
                if (person.LoginName.ToLower() == "admin")
                {
                    person.IsAdmin = true;
                    person.IsActive = true;
                }

                da.Persons.Add(person);

                da.SaveChanges();

                FormsAuthentication.SetAuthCookie(person.LoginName,false);
return Json(new object[] { true,"You have registered successfully!" });

}

}
这是我最终使用的版本,它基于@ AdamTuliper-MSFT的答案.它只能在登录后立即使用,但在重定向之前,允许其他代码访问HttpContext.User.

>如果已经过身份验证,请不要做任何事情
>不修改cookie,因为这应仅用于此请求的生命周期
>缩短一些东西,用userdata更安全一些(永远不应该为null,但……)

在调用SetAuthCookie()后调用此方法,如下所示:

// in login function
FormsAuthentication.SetAuthCookie(model.UserName,model.RememberMe);
AuthenticateThisRequest();

private void AuthenticateThisRequest()
{
    //NOTE:  if the user is already logged in (e.g. under a different user account)
    //       then this will NOT reset the identity information.  Be aware of this if
    //       you allow already-logged in users to "re-login" as different accounts 
    //       without first logging out.
    if (HttpContext.User.Identity.IsAuthenticated) return;

    var name = FormsAuthentication.FormsCookieName;
    var cookie = Response.Cookies[name]; 
    if (cookie != null)
    {   
        var ticket = FormsAuthentication.Decrypt(cookie.Value);
        if (ticket != null && !ticket.Expired)
        {
            string[] roles = (ticket.UserData as string ?? "").Split(',');
            HttpContext.User = new GenericPrincipal(new FormsIdentity(ticket),roles);
        }
    }
}

编辑:删除对Request.Cookies的调用,如@ AdamTuplier-MSFT所述.

Asp.net System.Web.HttpContext.Current.Session null in global.asax

Asp.net System.Web.HttpContext.Current.Session null in global.asax

我有一个自定义安全主体对象,我在global.asax中为当前线程设置,一切都很好,没有问题.

但是,我只是添加一个动态图像功能,让一个页面提供图像,每当加载动态图像页面System.Web.HttpContext.Current.Session是null在global.asax,这阻止我设置安全校长是从那时开始的正常和级联问题.

通常,在用户登录时,在开始时的会话期间,global.asax中的Session仅为null,之后它始终可用于此单个异常.

当浏览器碰到原始页面中的图像时,加载动态图像页面,即

我猜这是浏览器在不发送一些凭据的情况下请求该页面的一个方面呢?

任何帮助将不胜感激.

解决方法

约翰,

我假设你正在为处理程序使用一个ashx处理程序.如果是这样,请务必从IRequiresSessionState派生例如:

public class Images : IHttpHandler,System.Web.SessionState.IRequiresSessionState
{ }

如果您不使用ashx,您可以描述动态图像页面的意思吗?

玩笑

关于c# – HttpContext.Current.Session为nullc#的session的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于.net HttpContext.Current.Request.RawUrl、.net – 为什么HttpContext.Current.Handler为null?、ajax – 设置HttpContext.Current.User、Asp.net System.Web.HttpContext.Current.Session null in global.asax的相关知识,请在本站寻找。

本文标签: