在ASP.NET中生成新的SessionId [英] Generating new SessionId in ASP.NET

查看:82
本文介绍了在ASP.NET中生成新的SessionId的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

登录后,我想生成一个新的SessionId.我找到了一种有效的解决方案,但它需要一些漂亮的技巧,并且要求应用程序具有完全信任" securityPolicy设置.

On login I want to generate a new SessionId. I have found one solution that works, but it requires some pretty hackish things and requires the app have Full Trust securityPolicy setting.

还有其他方法可以实现这一目标吗?

Is there any other way to achieve this?

推荐答案

看起来像这样:

Session.Abandon();
Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));

通过清除该cookie,将在服务器上创建一个具有新会话ID的新会话.

By clearing out that cookie, a new session with a new session ID will be created at the server.

(参考: Microsoft支持)

这是一个使用AJAX(使用jQuery)来调用服务器代码而不刷新页面的示例-它调用两次,一次删除第一个会话,一次生成一个新会话.也许有更好的方法,但这确实可行.

Here's an example using AJAX (with jQuery) to call the server code without a page refresh - it calls twice, once to remove the first session, and once to generate a new one. There may be a better way, but this does work.

function newSession() {
    jQuery.ajax({
        type: "POST",
        url: "WebForm1.aspx/ClearSession",
        data: "{}",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function () {
            jQuery.ajax({
                type: "POST",
                url: "WebForm1.aspx/NewSession",
                data: "{}",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function () { console.log("Success!"); },
                error: function (x, y, z) {
                    console.log("Failure!");
                }
            });
        },
        error: function (x, y, z) {
            console.log("Failure!");
        }
    });
}

并在后面的代码中(对于WebForms-您也可以使用MVC控制器执行此操作):

And on the code-behind (for WebForms - you could also do this with an MVC controller):

[WebMethod]
public static void ClearSession()
{
    HttpContext.Current.Session.Abandon();
    HttpContext.Current.Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
}

[WebMethod]
public static void NewSession()
{
    HttpContext.Current.Session["x"] = 123;
}

这篇关于在ASP.NET中生成新的SessionId的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆