ASP.NET : 요청 간 Session.SessionID 변경
왜 속성은 않는 세션 ID 온 세션 요청 사이의 ASP.NET 페이지 변화 -object?
다음과 같은 페이지가 있습니다.
...
<div>
SessionID: <%= SessionID %>
</div>
...
브라우저와 관계없이 F5를 누를 때마다 출력이 계속 변경됩니다.
이것이 이유 다
쿠키 기반 세션 상태를 사용하는 경우 ASP.NET은 Session 개체를 사용할 때까지 세션 데이터에 저장소를 할당하지 않습니다. 결과적으로 세션 오브젝트에 액세스 할 때까지 각 페이지 요청에 대해 새 세션 ID가 생성됩니다. 응용 프로그램이 전체 세션에 대해 정적 세션 ID를 필요로하는 경우 응용 프로그램의 Global.asax 파일에서 Session_Start 메서드를 구현하고 세션 개체에 데이터를 저장하여 세션 ID를 수정하거나 다른 부분에서 코드를 사용할 수 있습니다 명시 적으로 Session 객체에 데이터를 저장하는 애플리케이션.
http://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate.sessionid.aspx
따라서 기본적으로 백엔드에서 세션 객체에 액세스하지 않으면 각 요청마다 새로운 sessionId가 생성됩니다.
편집하다
이 코드는 Global.asax 파일에 추가해야합니다. 세션 개체에 항목을 추가하므로 세션이 만료 될 때까지 수정합니다.
protected void Session_Start(Object sender, EventArgs e)
{
Session["init"] = 0;
}
Cladudio가 설명하는 것처럼 Session 객체가 초기화 된 경우에도이 문제가 발생할 수있는 더 교활한 이유가 있습니다.
Web.config에서 <httpCookies>
항목이 설정되어 requireSSL="true"
있지만 실제로 HTTPS를 사용하지 않는 항목 이있는 경우 : 특정 요청에 대해 세션 쿠키가 전송되지 않거나 반환되지 않을 수도 있습니다. 각 요청마다 새로운 세션으로 끝납니다.
나는이 변경이 어려운 것을 발견했으며, 소스 컨트롤의 여러 커밋 사이에서 몇 시간을주고받으며 어떤 변화가 내 응용 프로그램을 손상 시켰는지 알았습니다.
필자의 경우 세션 쿠키에 접두사 가 포함 된 도메인 이 www.
있고 no로 페이지를 요청하는 것으로 나타났습니다 www.
. URL에
추가하면 www.
즉시 문제가 해결되었습니다. 나중에 쿠키 도메인을 .mysite.com
대신 로 설정하도록 변경했습니다 www.mysite.com
.
Neville의 답변 (web.config에서 requireSSL = true 삭제)을 사용 하고 Joel Etherton의 코드를 약간 수정하면 사용자와 페이지에 따라 SSL 모드와 비 SSL 모드로 실행되는 사이트를 처리 해야하는 코드가 있습니다 (I 코드로 되돌아 가고 SSL에서 아직 테스트하지는 않았지만 작동해야한다고 기대합니다. 나중에 너무 바빠서 다시 돌아올 수 없으므로 다음과 같습니다.
if (HttpContext.Current.Response.Cookies.Count > 0)
{
foreach (string s in HttpContext.Current.Response.Cookies.AllKeys)
{
if (s == FormsAuthentication.FormsCookieName || s.ToLower() == "asp.net_sessionid")
{
HttpContext.Current.Response.Cookies[s].Secure = HttpContext.Current.Request.IsSecureConnection;
}
}
}
내 문제는 우리가 web.config 에서이 세트를 가지고 있다는 것입니다.
<httpCookies httpOnlyCookies="true" requireSSL="true" />
이는 비 SSL (기본값)에서 디버깅 할 때 인증 쿠키가 서버로 다시 전송되지 않음을 의미합니다. 이는 서버가 모든 요청에 대해 새 인증 쿠키 (새 세션과 함께)를 클라이언트에게 다시 보내는 것을 의미합니다.
수정은 web.config에서 requiresl을 false로 설정하고 web.release.config에서 true로 설정하거나 디버깅하는 동안 SSL을 켜는 것입니다.
Session_OnStart가 정의 및 / 또는 세션이 초기화 된 경우에도 세션 ID가 요청간에 변경되도록하는 다른 가능성은 URL 호스트 이름에 유효하지 않은 문자 (예 : 밑줄)가 포함되어 있다는 것입니다. 나는 이것이 IE 특정 (검증되지 않음)이라고 생각하지만 귀하의 URL이 (예 http://server_name/app
:)이면 IE는 모든 쿠키를 차단하고 요청간에 세션 정보에 액세스 할 수 없습니다.
실제로 각 요청은 서버에서 별도의 세션을 시작하므로 페이지에 여러 이미지, 스크립트 태그 등이 포함 된 경우 각 GET 요청은 서버에서 다른 세션을 발생시킵니다.
추가 정보 : http://support.microsoft.com/kb/316112
내 문제는 Microsoft MediaRoom IPTV 응용 프로그램과 관련이 있습니다. MPF MRML 응용 프로그램은 쿠키를 지원하지 않습니다. web.config에서 쿠키없는 세션을 사용하도록 변경하면 문제가 해결되었습니다.
<sessionState cookieless="true" />
쿠키가없는 ASP.NET : 여기에 관한 오래된 기사가 있습니다.
In my case this was happening a lot in my development and test environments. After trying all of the above solutions without any success I found that I was able to fix this problem by deleting all session cookies. The web developer extension makes this very easy to do. I mostly use Firefox for testing and development, but this also happened while testing in Chrome. The fix also worked in Chrome.
I haven't had to do this yet in the production environment and have not received any reports of people not being able to log in. This also only seemed to happen after making the session cookies to be secure. It never happened in the past when they were not secure.
in my case it was because I was modifying session after redirecting from a gateway in an external application, so because I was using IP instead on localhost in that page url it was actually considered different website with different sessions.
In summary
pay more attention if you are debugging a hosted application on IIS instead of IIS express and mixing your machine http://Ip and http://localhost in various pages
Be sure that you do not have a session timeout that is very short, and also make sure that if you are using cookie based sessions that you are accepting the session.
The FireFox webDeveloperToolbar is helpful at times like this as you can see the cookies set for your application.
Session ID resetting may have many causes. However any mentioned above doesn't relate to my problem. So I'll describe it for future reference.
In my case a new session created on each request resulted in infinite redirect loop. The redirect action takes place in OnActionExecuting event.
Also I've been clearing all http headers (also in OnActionExecuting event using Response.ClearHeaders method) in order to prevent caching sites on client side. But that method clears all headers including informations about user's session, and consequently all data in Temp storage (which I was using later in program). So even setting new session in Session_Start event didn't help.
To resolve my problem I ensured not to remove the headers when a redirection occurs.
Hope it helps someone.
I ran into this issue a different way. The controllers that had this attribute [SessionState(SessionStateBehavior.ReadOnly)]
were reading from a different session even though I had set a value in the original session upon app startup. I was adding the session value via the _layout.cshtml (maybe not the best idea?)
It was clearly the ReadOnly causing the issue because when I removed the attribute, the original session (and SessionId) would stay in tact. Using Claudio's/Microsoft's solution fixed it.
I'm on .NET Core 2.1 and I'm well aware that the question isn't about Core. Yet the internet is lacking and Google brought me here so hoping to save someone a few hours.
Startup.cs
services.AddCors(o => o.AddPolicy("AllowAll", builder =>
{
builder
.WithOrigins("http://localhost:3000") // important
.AllowCredentials() // important
.AllowAnyMethod()
.AllowAnyHeader(); // obviously just for testing
}));
client.js
const resp = await fetch("https://localhost:5001/api/user", {
method: 'POST',
credentials: 'include', // important
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
Controllers/LoginController.cs
namespace WebServer.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UserController : ControllerBase
{
[HttpPost]
public IEnumerable<string> Post([FromBody]LoginForm lf)
{
string prevUsername = HttpContext.Session.GetString("username");
Console.WriteLine("Previous username: " + prevUsername);
HttpContext.Session.SetString("username", lf.username);
return new string[] { lf.username, lf.password };
}
}
}
세션 쓰기 및 읽기가 작동하지만 쿠키가 브라우저로 전달되지 않는 것 같습니다. 적어도 어디서나 "Set-Cookie"헤더를 찾을 수 없습니다.
참고 URL : https://stackoverflow.com/questions/2874078/asp-net-session-sessionid-changes-between-requests
'Programing' 카테고리의 다른 글
ImportError : 이름이 notebook.notebookapp 인 모듈이 없습니다. (0) | 2020.06.26 |
---|---|
VBA에서 현재 워크 시트의 경로를 얻는 방법은 무엇입니까? (0) | 2020.06.26 |
TCP 소켓과 웹 소켓의 차이점, 다시 한 번 (0) | 2020.06.26 |
datagridview에서 행 색상을 변경하는 방법은 무엇입니까? (0) | 2020.06.26 |
csv.Error : 반복자는 바이트가 아닌 문자열을 반환해야합니다 (0) | 2020.06.26 |