How to increase Session Timeout in Asp.net C# - 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";

Related

Reading AuthorizationSection from web.config provides incorrect values

Edit #2: config.FilePath is showing that it's looking at a different file than what I'm expecting: "C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config". I was expecting it to use the web.config in my project. Need to figure out why that's happening.
I have a method in my web API where I'm trying to read the values from the authorization section in my web.config. Based on what I've found, this should work:
public AuthorizationSetting GetAuthorizationSettings()
{
var config = WebConfigurationManager.OpenWebConfiguration(null);
var section = config.GetSection("system.web/authorization") as AuthorizationSection;
foreach (AuthorizationRule rule in section.Rules)
{
if (rule.Action.ToString().ToLower() == "allow")
{
Debug.WriteLine(rule);
}
}
return new AuthorizationSetting();
}
And this is the section of the web.config that contains the authorization info:
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<identity impersonate="true" />
<authentication mode="Windows" />
<authorization>
<allow roles="role1,role2,role3"/>
<deny users="*"/>
</authorization>
</system.web>
You can see that there is one allow and one deny. When I run the code, it appears that there is only one rule. Shouldn't there be two since there is an allow and a deny? And the one rule looks to have an Action of Allow and "*" for Users. That's not what's in the web.config. What am I missing here?
** Edit **
I've considered the possibility that it's reading a different web.config file. But there is only one other web.config file in the solution (under Views). I also changed it to have the same authorization section, but I still get the same result.
As you already figured out using Null in for the path parameter of OpenWebConfiguration loads the server root web.config in
%SystemRoot%\Microsoft.NET\Framework64\v4.0.30319\Config\
the documentation says:
The virtual path to the configuration file. If null, the root Web.config file is opened.
but one could assume it would be the root web config of the site, not the server. Anyway, try using:
var config = WebConfigurationManager.OpenWebConfiguration("~");

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

Getting Authentication Form Timeout

I'm using the following code in Global.asax.cs (which I believe is an MVC conventional name)
Configuration conn = WebConfigurationManager.OpenWebConfiguration("");
AuthenticationSection section = (AuthenticationSection)conn.SectionGroups.Get("system.web").Sections.Get("authentication");
Application["Expire"] = System.Convert.ToInt64(section.Forms.Timeout.TotalMinutes);
to grab the timeout from the following form in Web.Config
<authentication mode="Forms">
<forms name=".FooAuth" path="/" protection="All" requireSSL="false" loginUrl="~/Member/Login" timeout="30" />
</authentication>
Application["Expire"] always gets 30, despite any changes to the timeout variable. I'm thinking that I must be changing the wrong variable somewhere. Thanks in advance for the help!

SessionState Timeout never fires

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

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