简体   繁体   English

在ASPX WebMethod的AJAX调用之间ASP.Net会话更改

[英]ASP.Net Session changes between AJAX calls to ASPX WebMethod

I have a single page application that starts off with default.aspx creating the basic HTML layout and then I use AJAX calls to get data from static WebMethods in other aspx pages. 我有一个以default.aspx开始的单页面应用程序,它创建了基本的HTML布局,然后使用AJAX调用从其他aspx页面中的静态WebMethods获取数据。 I also have a KeepAlive.aspx that reloads every once in a while to keep the session alive. 我还有一个KeepAlive.aspx,它每隔一段时间会重新加载一次,以保持会话正常运行。

The login form that appears initially calls the login webmethod which uses an external web service to login and store user information in the session. 最初出现的登录表单称为登录Web方法,该方法使用外部Web服务在会话中登录和存储用户信息。 I use HttpContext.Current.Session to get and set values in the session. 我使用HttpContext.Current.Session来获取和设置会话中的值。

The very next web method that I call is to getuserpreferences from the external web service using identity information obtained at login time. 我要调用的下一个Web方法是使用登录时获得的身份信息从外部Web服务获取用户首选项。

This is all working fine and dandy on various IIS servers. 在各种IIS服务器上,这一切工作正常且繁琐。 Recently we deployed this on a new server and it is not working there. 最近,我们在新服务器上部署了该服务器,但该服务器无法在其中运行。

It does successfully login and saves the user values in session, but when the next ajax call to getuserpreferences happens, the getuserpreferences web method tries to get the session values... and it is NOT there any more! 它确实成功登录并在会话中保存了用户值,但是当下一次对getuserpreferences的ajax调用发生时,getuserpreferences Web方法将尝试获取会话值...并且它不再存在!

I put in a bunch of logging and saw that session Id is changing! 我记录了一堆日志,看到会话ID正在更改! The login session id is different from the session id that I see from get userpreferences, even though both use HttpContext.Current.Session. 登录会话ID与我从get userpreferences中看到的会话ID不同,即使它们都使用HttpContext.Current.Session。

On the servers that it does work, sometimes (randomly?) it does behave in a similar way: it loses session values and throws me back to login. 在确实可以正常工作的服务器上,有时(随机地?)的行为也类似:它丢失了会话值并使我重新登录。

Please provide help/tips to trace this issue and ensure the same session continues across ajax calls. 请提供帮助/技巧来跟踪此问题,并确保同一会话在ajax调用中继续进行。 This is not an MVC or WebAPI project; 这不是MVC或WebAPI项目。 it is a simple aspx application. 这是一个简单的aspx应用程序。

UPDATE (Jan 8) : I found the difference in behavior between the instances where this works and where it doesn't: ASP.Net_SessionId cookie value is being set where it works, but in this case it is not being set and is therefore not maintaining session state. UPDATE(1月8日) :我发现在可行的实例与不可行的实例之间,行为上的差异:在可行的地方设置了ASP.Net_SessionId cookie值,但是在这种情况下,没有设置,因此没有保持会话状态。 Now I need to figure out why it is not setting. 现在,我需要弄清楚为什么它没有设置。

Update 2 (Jan 8) : When we installed a certificate on the server and implemented https, the session Id cookie started appearing. 更新2(1月8日) :当我们在服务器上安装证书并实现https时,会话ID cookie开始出现。 So although the issue is no longer urgent, I do want to find out why HTTP did not work. 因此,尽管这个问题不再紧急,但我确实想弄清楚为什么HTTP不起作用。

Code: 码:

WebServiceHelper.js WebServiceHelper.js

    WebServiceHelper.prototype.invokeServiceMethod = function(serviceName, methodName, params, returntype) {
    var self = this;
    var obj = {};
    var def = $.Deferred();
    var url = serviceName + "/" + methodName;
    $.support.cors = true;
    $.ajax({
        url: url,
        data: ko.toJSON(params),
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function(mydata) {

            if (mydata && mydata.d) {

                    def.resolve(mydata.d);
                }                

        },
        error: function(msg) {

                def.reject(msg);
        }
    });

    return def.promise();
};

Data Provider.js: 数据Provider.js:

   DataProvider.prototype.loginUser = function(email, password, token) {
    var self = this;
    var def = $.Deferred();

    var webServiceHelper = new WebServiceHelper();

    webServiceHelper.invokeServiceMethod("Login.aspx", "LoginUser", { email: email, password: password, token: token }, "json").done(function (retObj) {
        self.userObj = retObj.userinfo;
        self.loginTime = new Date();
        self.loadInitialData();
        def.resolve();
    }).fail(
        function(retObj1) {
                def.reject(retObj1);
        });

    return def.promise();
};

Preference Manager.js 首选项Manager.js

    PreferenceManager.prototype.invokeGetPreferences = function (prefKey) {
    var self = this;

    var def = $.Deferred();

    var webServiceHelper = new WebServiceHelper();

    webServiceHelper.invokeServiceMethod("WebMethods.aspx", "GetPreferences", { key: prefKey }, "json").done(function (retObj) {
        def.resolve(retObj);
    }).fail(
        function (retObj1) {
                def.reject(retObj1);
        });

    return def.promise();

};

Login.aspx.cs: Login.aspx.cs:

        [WebMethod(EnableSession=true)]
    public static string LoginUser(string email, string password, string token)
    {
        if (Authenticate(email, password, token))
        {
            HttpContext.Current.Session["vanalyticsLastLoginDateTime"] = DateTime.Now;

            var userjson =  GetUserJson();

            Logger.Debug("Login - Session Id {0} - Returning user json {1}", HttpContext.Current.Session.SessionID, userjson);

            return userjson;
        }

        return "Error: " + _validationError;
    }

        private static bool Authenticate(string stremail, string strpassword, string token)
    {
        var vplug = new vPlugin();

        HttpContext.Current.Session.Remove("vUserInfo");

        vplug.Authenticate(HttpContext.Current, appsurl, stremail, strpassword, token);

        _validationError = vplug.LastException != null ? vplug.LastException.Message : null;

        return (HttpContext.Current.Session["vUserInfo"] != null);
    }

vPlugin code: (eventually calls setuser) vPlugin代码:(最终调用setuser)

 private void SetUser(HttpContext obj, userInfo user)
    {
        HttpSessionState session = obj.Session;

        session["vUserInfo"] = user;
        ....
        session["vDataToken"] = setting.ContainsKey("token") ? setting["token"] : "0-0";
    }

WebMethods.aspx: WebMethods.aspx:

    [WebMethod(EnableSession=true)]
    public static string GetPreferences(string key)
    {
        var myadr = new ADR.VrtDataService { Timeout = 20000 };

        var token = GetTokenFromSession();

        try
        {
            var result = myadr.getPreference(token, key);

            myadr.Dispose();

            return result;
        }
        catch (Exception ex)
        {
            return "Error: " + ex.Message;
        }
    }

       public static string GetTokenFromSession()
    {
        var token = "";

        var val2 = HttpContext.Current.Session["vDataToken"];

        if (val2 != null)
        {
            token = (string) val2;
        }
        else
        {
            Logger.Error("Token is blank, session id is " + HttpContext.Current.Session.SessionID);
        }

        return token;
    }

I am getting 'Token is blank' and the session id is different from the Id logged by the login method earlier. 我得到的是“令牌为空”,并且会话ID与之前通过登录方法记录的ID不同。

Also, please note that the entire code is in JavaScript and aspx only serves as RESTful API with session. 另外,请注意,整个代码都使用JavaScript,aspx仅用作带有会话的RESTful API。

很简单,只需使用HttpContext.Current.Session["user_id"] = ""

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM