SessionState Timeout never fires - c#

What am I doing wrong. The sessionState Timeout never fires,It only fires after 24 hours, I want to let it fire in 20 minutes on my webpage. In the web.config I handle the sessionstate like this:
<sessionState cookieless="false" mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes"
timeout="1" stateNetworkTimeout="1"/>
timeout="1" is on purpose, for testing.
And in the code I check on which session I am by calling Session.SessionID.ToString()

if you're using InProc, you dont need stateConnectionString, sqlConnectionString and stateNetworkTimeout. Try removing these, and see if this works as you'd like.

SessionState Timeout only fires when session state mode is InProc.

I've figured out that if I change cookieless=false -> true that it works , but now the sessionid is shown in my URL. How could I get rid of the sessionid in my url.
its like http://domain.com/(S(nvqmpm45j2fnnc21w00sjx55))/index.aspx

Related

Best way to redirect user to Login page on cache lost

What is the best way to redirect user to login when cache is lost?
At moment I'm doing this:
if (Session["Id"] == null)
{
return RedirectToAction("Login", "Home");
}
But with this method, it put this code in every function, is there any other way to do this in the entire program? I tried search by doing this from web.config, but no results.
Assuming you are using Form-based authentication and permitting access to only authorised users then this could be achieved through making changes in web.config
<authentication mode="Forms">
<forms loginUrl="login.aspx" defaultUrl="default.aspx" name=".YourApplication" timeout="60" cookieless="AutoDetect" />
</authentication>
<authorization>
<deny users="?" />
</authorization>
the loginUrl property tells the server where to direct the user if he is not logged in, and the defaultUrl property tells the server where to direct him after the user is logged.
the deny users="?" tells the server to deny any user that is not authenticated and directs him to the loginUrl page
In the codebehind of the login page, you need something like this after you check the credentials inserted:
FormsAuthentication.RedirectFromLoginPage(userName.Text, True)
Reference
private const string GlobalAuthKey = "GlobalAuthTime";
You can insert all auth user info in authList.
HttpRuntime.Cache.Insert(GlobalAuthKey, authList);
Then Get cache :
var authList = HttpRuntime.Cache.Get(GlobalAuthKey) as List<AuthInfo> ?? new
List<AuthInfo>();
After that you check this specific user login info,and you force your user by this desire condition.Hopefully You understand.

How to increase Session Timeout in Asp.net C#

<system.web>
<sessionState timeout="20" mode="InProc"/>
</system.web>
Is there anything else I need to do?
That should be alright but do also check if you are overriding that value in your code behind somewhere by saying below. Probably in the Global.asax file under Session_Start()
Session.Timeout = "40";

IIS8 MVC asp.NET Session not working. Getting null object reference error

Can't get session variables working, I've tried all the solutions I could find online.
On page 1, I call the following in the c# model
HttpContext.Current.Session["lol1"] = "123";
Later on I use an ajax call to return this session variable to me in the c# model,
return HttpContext.Current.Session["lol1"].ToString();
In javascript, I pick it up in the ajax success function and put it in an alert box with alert(e);
I get an null object reference error. Seems like my variable didn't save into the session. This all works fine on localhost via debug, including the alert.
Things I have tried (currently set):
-DefaultAppPool setting Maximum Worker Processes: 1
-IIS manager->ASP->Services->Session Properties->Enable Session State:true
-IIS manager->Session State->In process
-In my solution web.config:
<system.web>
<sessionState mode="InProc" timeout="25"></sessionState>
</system.web>
<system.webServer>
<modules>
<remove name="Session" />
<add name="Session" type="System.Web.SessionState.SessionStateModule"/>
</modules>
</system.webServer>
Try setting the SessionStateBehavior in your controller. For example:
[SessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)]
It is recommended to use ReadOnly if you only need to read from Session and not write to it to prevent blocking.
Link to Microsoft's SessionStateBehavior enumeration.
(for more info on ASP.NET's blocking when controllers use writable sessions see this link: Does Session State read/write everything when you access with DynamoDB)
Hope this helps!
Regards,
Ross

Custom SessionState Oracle SessionStateStoreProviderBase

I created a custom session class and inherited the SessionStateStoreProviderBase connecting the oracle.
I'm using this how-to, just replace with the connection classes of Oracle.DataAccess.
Until then everything working locally but when I publish on iis 7.5 server with a custom class SessionStateStoreProviderBase is still working, but the variable "session" (HttpSessionStateBase) are zero (null). Ex: Session["idUser"].
Anything I'm forgetting? Please I need help, because the documentation does not seem to be clear about that.
My web.config:
<sessionState timeout="30" mode="Custom" cookieless="false" customProvider="CustomSessionProvider" sessionIDManagerType="namespace.CustomSessionIdManager">
<providers>
<add name="CustomSessionProvider" type="namespace.SessionDataProvider" connectionStringName="connectionOracle" />
</providers>
</sessionState>
<authentication mode="Forms">
<forms loginUrl="~/Login" defaultUrl="~/Inicio" />
</authentication>
Error Log IIS:
#Software: Microsoft Internet Information Services 7.5
#Version: 1.0
#Date: 2014-08-05 01:14:37
#Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) sc-status sc-substatus sc-win32-status time-taken
2014-08-05 01:14:37 192.168.xxx.xx GET / - 80 - 10.100.xxx.xx Mozilla/5.0+(Windows+NT+6.1;+WOW64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/34.0.1847.131+Safari/537.36 302 0 0 6239
2014-08-05 01:14:37 192.168.xxx.xx GET /Inicio - 80 - 10.100.xxx.xx Mozilla/5.0+(Windows+NT+6.1;+WOW64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/34.0.1847.131+Safari/537.36 500 0 0 374
Exception in the controller:
object reference not set to an instance of an object
Verify before if session is null.
Thank you.
Debugging my best custom class session, I noticed that when trying to convert an integer he took exception, but it worked localhost, but not on the server. Skirted the problem by making another type of conversion, Convert using the framework rather than the GetInt32 odt Oracle. Do not know why so it functioned, but not on the server, and reproduce the same situation.
With this error he did not arrive in the method 'CreateNewStoreData'.
Works well. Ex: reader.IsDBNull(2) ? 0 : Convert.ToInt32(reader2);
Does not work well. Ex: reader.IsDBNull(2) ? 0 : reader.GetInt32(2);
Thanks for your help and attention.
Thank 'Alireza'! :)

Context.User losing Roles after being assigned in Global.asax.Application_AuthenticateRequest

I am using Forms authentication in my asp.net (3.5) application. I am also using roles to define what user can access which subdirectories of the app. Thus, the pertinent sections of my web.config file look like this:
<system.web>
<authentication mode="Forms">
<forms loginUrl="Default.aspx" path="/" protection="All" timeout="360" name="MyAppName" cookieless="UseCookies" />
</authentication>
<authorization >
<allow users="*"/>
</authorization>
</system.web>
<location path="Admin">
<system.web>
<authorization>
<allow roles="Admin"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
Based on what I have read, this should ensure that the only users able to access the Admin directory will be users who have been Authenticated and assigned the Admin role.
User authentication, saving the authentication ticket, and other related issues all work fine. If I remove the tags from the web.config file, everything works fine. The problem comes when I try to enforce that only users with the Admin role should be able to access the Admin directory.
Based on this MS KB article along with other webpages giving the same information, I have added the following code to my Global.asax file:
protected void Application_AuthenticateRequest(Object sender, EventArgs e) {
if (HttpContext.Current.User != null) {
if (Request.IsAuthenticated == true) {
// Debug#1
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Context.Request.Cookies[FormsAuthentication.FormsCookieName].Value);
// In this case, ticket.UserData = "Admin"
string[] roles = new string[1] { ticket.UserData };
FormsIdentity id = new FormsIdentity(ticket);
Context.User = new System.Security.Principal.GenericPrincipal(id, roles);
// Debug#2
}
}
}
However, when I try to log in, I am unable to access the Admin folder (get redirected to login page).
Trying to debug the issue, if I step through a request, if I execute Context.User.IsInRole("Admin") at the line marked Debug#1 above, it returns a false. If I execute the same statement at line Debug#2, it equals true. So at least as far as Global.asax is concerned, the Role is being assigned properly.
After Global.asax, execution jumps right to the Login page (since the lack of role causes the page load in the admin folder to be rejected). However, when I execute the same statement on the first line of Page_Load of the login, it returns false. So somewhere after Application_AuthenticateRequest in Global.asax and the initial load of the WebForm in the restricted directory, the role information is being lost, causing authentication to fail (note: in Page_Load, the proper Authentication ticket is still assigned to Context.User.Id - only the role is being lost).
What am I doing wrong, and how can I get it to work properly?
Update: I entered the solution below
Here was the problem and solution:
Earlier in development I had gone to the Website menu and clicked on Asp.net configuration. This resulted in the following line being added to the web.config:
<system.web>
<roleManager enabled="true" />
</system.web>
From that point on, the app was assuming that I was doing roles through the Asp.net site manager, and not through FormsAuthentication roles. Thus the repeated failures, despite the fact that the actual authentication and roles logic was set up correctly.
After this line was removed from web.config everything worked perfectly.
this is just a random shot, but are you getting blocked because of the order of authorization for Admin? Maybe you should try switching your deny all and your all Admin.
Just in case it's getting overwritten by the deny.
(I had code samples in here but they weren't showing up.

Categories