C# 我可以将 ASP.Net 会话 ID 放在隐藏的表单字段中吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I put an ASP.Net session ID in a hidden form field?
提问by Josh Hinman
I'm using the Yahoo Uploader, part of the Yahoo UI Library, on my ASP.Net website to allow users to upload files. For those unfamiliar, the uploader works by using a Flash applet to give me more control over the FileOpen dialog. I can specify a filter for file types, allow multiple files to be selected, etc. It's great, but it has the following documented limitation:
我在我的 ASP.Net 网站上使用雅虎上传器,雅虎 UI 库的一部分,以允许用户上传文件。对于那些不熟悉的人,上传器通过使用 Flash 小程序来让我更好地控制 FileOpen 对话框。我可以为文件类型指定过滤器,允许选择多个文件等。这很棒,但它有以下记录限制:
Because of a known Flash bug, the Uploader running in Firefox in Windows does not send the correct cookies with the upload; instead of sending Firefox cookies, it sends Internet Explorer's cookies for the respective domain. As a workaround, we suggest either using a cookieless upload method or appending document.cookie to the upload request.
由于已知的 Flash 错误,在 Windows 的 Firefox 中运行的上传器不会随上传发送正确的 cookie;它不会发送 Firefox cookie,而是发送 Internet Explorer 的相应域的 cookie。作为解决方法,我们建议使用无 cookie 上传方法或将 document.cookie 附加到上传请求。
So, if a user is using Firefox, I can't rely on cookies to persist their session when they upload a file. I need their session because I need to know who they are! As a workaround, I'm using the Application object thusly:
因此,如果用户使用 Firefox,我不能依靠 cookie 在他们上传文件时保留他们的会话。我需要他们的会议,因为我需要知道他们是谁!作为一种解决方法,我正在使用 Application 对象:
Guid UploadID = Guid.NewGuid();
Application.Add(Guid.ToString(), User);
So, I'm creating a unique ID and using it as a key to store the Page.User
object in the Application scope. I include that ID as a variable in the POST when the file is uploaded. Then, in the handler that accepts the file upload, I grab the User object thusly:
因此,我创建了一个唯一 ID 并将其用作将Page.User
对象存储在 Application 范围内的键。上传文件时,我将该 ID 作为变量包含在 POST 中。然后,在接受文件上传的处理程序中,我这样抓取 User 对象:
IPrincipal User = (IPrincipal)Application[Request.Form["uploadid"]];
This actually works, but it has two glaring drawbacks:
这确实有效,但它有两个明显的缺点:
If IIS, the app pool, or even just the application is restarted between the time the user visits the upload page, and actually uploads a file, their "uploadid" is deleted from application scope and the upload fails because I can't authenticate them.
If I ever scale to a web farm (possibly even a web garden) scenario, this will completely break. I might not be worried, except I do plan on scaling this app in the future.
如果 IIS、应用程序池,甚至只是应用程序在用户访问上传页面和实际上传文件之间重新启动,则它们的“uploadid”将从应用程序范围中删除并且上传失败,因为我无法对其进行身份验证.
如果我曾经扩展到网络农场(甚至可能是网络花园)场景,这将完全中断。我可能并不担心,除非我计划在未来扩展这个应用程序。
Does anyone have a better way? Is there a way for me to pass the actual ASP.Net session ID in a POST variable, then use that ID at the other end to retrieve the session?
有没有人有更好的方法?有没有办法让我在 POST 变量中传递实际的 ASP.Net 会话 ID,然后在另一端使用该 ID 来检索会话?
I know I can get the session ID through Session.SessionID
, and I know how to use YUI to post it to the next page. What I don't know is how to use that SessionID
to grab the session from the state server.
我知道我可以通过 获取会话 ID Session.SessionID
,并且我知道如何使用 YUI 将其发布到下一页。我不知道如何使用它SessionID
从状态服务器获取会话。
Yes, I'm using a state server to store the sessions, so they persist application/IIS restarts, and will work in a web farm scenario.
是的,我使用状态服务器来存储会话,因此它们会持续应用程序/IIS 重新启动,并且可以在 Web 场场景中工作。
采纳答案by Seb Nilsson
Hereis a post from the maintainer of SWFUploadwhich explains how to load the session from an ID stored in Request.Form. I imagine the same thing would work for the Yahoo component.
这是SWFUpload维护者的一篇文章,解释了如何从存储在 Request.Form 中的 ID 加载会话。我想同样的事情也适用于雅虎组件。
Note the security disclaimers at the bottom of the post.
请注意帖子底部的安全免责声明。
By including a Global.asax file and the following code you can override the missing Session ID cookie:
通过包含 Global.asax 文件和以下代码,您可以覆盖缺少的会话 ID cookie:
using System;
using System.Web;
public class Global_asax : System.Web.HttpApplication
{
private void Application_BeginRequest(object sender, EventArgs e)
{
/*
Fix for the Flash Player Cookie bug in Non-IE browsers.
Since Flash Player always sends the IE cookies even in FireFox
we have to bypass the cookies by sending the values as part of the POST or GET
and overwrite the cookies with the passed in values.
The theory is that at this point (BeginRequest) the cookies have not been ready by
the Session and Authentication logic and if we update the cookies here we'll get our
Session and Authentication restored correctly
*/
HttpRequest request = HttpContext.Current.Request;
try
{
string sessionParamName = "ASPSESSID";
string sessionCookieName = "ASP.NET_SESSIONID";
string sessionValue = request.Form[sessionParamName] ?? request.QueryString[sessionParamName];
if (sessionValue != null)
{
UpdateCookie(sessionCookieName, sessionValue);
}
}
catch (Exception ex)
{
// TODO: Add logging here.
}
try
{
string authParamName = "AUTHID";
string authCookieName = FormsAuthentication.FormsCookieName;
string authValue = request.Form[authParamName] ?? request.QueryString[authParamName];
if (authValue != null)
{
UpdateCookie(authCookieName, authValue);
}
}
catch (Exception ex)
{
// TODO: Add logging here.
}
}
private void UpdateCookie(string cookieName, string cookieValue)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(cookieName);
if (cookie == null)
{
HttpCookie newCookie = new HttpCookie(cookieName, cookieValue);
Response.Cookies.Add(newCookie);
}
else
{
cookie.Value = cookieValue;
HttpContext.Current.Request.Cookies.Set(cookie);
}
}
}
Security Warning:Don't just copy and paste this code in to your ASP.Net application without knowing what you are doing. It introduces security issues and possibilities of Cross-site Scripting.
安全警告:不要只是在不知道您在做什么的情况下将此代码复制并粘贴到您的 ASP.Net 应用程序中。它介绍了跨站点脚本的安全问题和可能性。
回答by Espo
The ASP.Net Session ID is stored in Session.SessionID
so you could set that in a hidden field and then post it to the next page.
ASP.Net 会话 ID 存储在其中,Session.SessionID
因此您可以将其设置在隐藏字段中,然后将其发布到下一页。
I think, however, that if the application restarts, the sessionID will expire if you do not store your sessions in sql server.
但是,我认为,如果应用程序重新启动,如果您不将会话存储在 sql server 中,则 sessionID 将过期。
回答by Seb Nilsson
You can get your current SessionID from the following code:
您可以从以下代码中获取当前的 SessionID:
string sessionId = HttpContext.Current.Session.SessionID;
Then you can feed that into a hidden field maybe and then access that value through YUI.
然后您可以将其输入到隐藏字段中,然后通过 YUI 访问该值。
It's just a get, so you hopefully won't have any scaling problems. Security-problems though, that I don't know.
这只是一个获取,所以你希望不会有任何缩放问题。安全问题,我不知道。
回答by Pluto
Relying on this blog post, here's a function that should get you the session for any user based on the session ID, though it's not pretty:
依靠这篇博文,这里有一个函数可以根据会话 ID 为您获取任何用户的会话,尽管它并不漂亮:
public SessionStateStoreData GetSessionById(string sessionId)
{
HttpApplication httpApplication = HttpContext.ApplicationInstance;
// Black magic #1: getting to SessionStateModule
HttpModuleCollection httpModuleCollection = httpApplication.Modules;
SessionStateModule sessionHttpModule = httpModuleCollection["Session"] as SessionStateModule;
if (sessionHttpModule == null)
{
// Couldn't find Session module
return null;
}
// Black magic #2: getting to SessionStateStoreProviderBase through reflection
FieldInfo fieldInfo = typeof(SessionStateModule).GetField("_store", BindingFlags.NonPublic | BindingFlags.Instance);
SessionStateStoreProviderBase sessionStateStoreProviderBase = fieldInfo.GetValue(sessionHttpModule) as SessionStateStoreProviderBase;
if (sessionStateStoreProviderBase == null)
{
// Couldn't find sessionStateStoreProviderBase
return null;
}
// Black magic #3: generating dummy HttpContext out of the thin air. sessionStateStoreProviderBase.GetItem in #4 needs it.
SimpleWorkerRequest request = new SimpleWorkerRequest("dummy.html", null, new StringWriter());
HttpContext context = new HttpContext(request);
// Black magic #4: using sessionStateStoreProviderBase.GetItem to fetch the data from session with given Id.
bool locked;
TimeSpan lockAge;
object lockId;
SessionStateActions actions;
SessionStateStoreData sessionStateStoreData = sessionStateStoreProviderBase.GetItem(
context, sessionId, out locked, out lockAge, out lockId, out actions);
return sessionStateStoreData;
}