MVC3 destroying session on redirecttoaction - asp.net-mvc-3

I have an issue with sessions in an MVC3 application. In one controller I am receiving a post request then adding the value to session before redirecting to the controllers get method.
The issue is that in the GET request the session value returns null even though in the POST request the sessions value was set.
[HttpPost]
public ActionResult findPerson(PersonSearch searchDetails)
{
Session["FindPersons"] = searchDetails;
return RedirectToAction("findperson");
}
[HttpGet]
public ActionResult findperson()
{
PersonSearch searchDetails = (PersonSearch)Session["FindPersons"];

Solution:
Some nutter named the session state cookie name in the web.config and the authentication forms name the same thing.
<sessionState timeout="20" cookieName="Spacer" />
<forms loginUrl="/spacer/login" name="Spacer" timeout="2200" />
Obviously the effect it was having was trying to store session and cookies in something called the same thing. Im very surprised this just did not blow up.
Thanks for your help #dknaack, I wouldnt have spotted this so quickly if you were not pointing me in the correct direction.

I tryed your code and don't run in this problem. So i looked at the ASP.NET Forum.
There is a post RedirectToAction looses session in IIS
I've just run into this issue. Its not related to redirect to action itself but the app pool. What fixed it for me was deleting the app pool the site was running under in IIS and re-creating it. Works fine now. Source

Related

CakePHP: can't access the Session when making AJAX call

This question is for CakePHP 4.3:
In my action, I am accessing the session. For a normal GET request, everything works fine. If I call the same action through an AJAX request, I do not have access to the session. Why is that?
For example, even this does not work:
public function select3() {
debug($this->request->getSession()->read());
}
For a GET request, the session is printed. For an AJAX call, an empty array is printed.
Is the AppController NOT called for an AJAX request?
Any help is appreciated!
First, thanks to "ndm" for your offered help.
I solved it after seeing that something was mixed up with the URLS.
The URL has "server-4.2" in it, and "server" is a link to it.
Both "server-4.2" and "server" seemed to have confused the Authentication controller.
Glad it works now.

This page isn't redirecting properly error with MVC3 + AJAX + Forms Authentication

EDIT: Removed non-relevant code/desc, since the issue was not just to do with the initial code there.
I have an MVC3 based application that uses a lot of Ajax calls (such as with jqGrid) and Forms Authentication. I also use the [Authorize] attribute on certain controller/actions that I call with Ajax in most cases. Every so often my application falls over with a 'This page isn't redirecting properly' or a 'this page has a redirect loop'.
I checked this out with fiddler. After logging in as a user and trying to access pages that require authentication, sometimes I get redirected to Account/LogOn which then goes into an infinite loop. This usually happens when I'm calling any controller/action with an Authorize attribute with an Ajax call. The application seems to send out a 302 redirect to Account/Logon. The Account/Logon call then seems to redirect to itself. And the textView on Fiddler shows the following.
<html><head><title>Object moved</title></head><body>
<h2>Object moved to here.</h2>
</body></html>
I have the following in my Global.asax file
protected void Application_EndRequest()
{
var context = new HttpContextWrapper(this.Context);
//if we are an ajax request and forms authentication caused a 302, then we actually need to do a 401
if (System.Web.Security.FormsAuthentication.IsEnabled && context.Response.StatusCode == 302 && context.Request.IsAjaxRequest())
{
context.Response.Clear();
context.Response.StatusCode = 401;
}
}
And this in my main Layout page
<script type="text/javascript">
$(document).ajaxError(function (xhr, props) {
if (props.status == 401) {
location.reload();
}
});
</script>
My web.config setting for Forms authentication has this
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880"/>
</authentication>
The redirect starts every so often and it is not with the same controller/action either. Just seems quite random. I am not sure if the cookie is expiry for the user and causing this issue for some reason or if it is an issue with the application pool recycling. Any suggestions on how to get around this would be most appreciated. Been struggling with this the last few days now, so any help from the experts will be great. Thank You
decorate your action method with Authorize attribute to make it available to authenticated/logged in users, after that check user role.
I don't see a loop in the above code. But maybe in one of controller1 or controller2 you have a redirect back to this home/index action.
I would suggest to run fiddler while testing the site, when a redirect loop happens you can easily detect it there, and then it is easier to find out what's wrong with the code.
Please see the answer in the linked question. This was the resolution to my redirect loop problem. Thank you for all your inputs.
IIS Session timeout and Forms Authentication loop

After Wicket session timeout - pageParameters are null

I'm using wicket 6.
My application is based on WebPages created with pageParameters in the constructor. I'm using also a pageParameter country that is a path-parameter defined with:
mountPage("/${country}/pagepath", MyPage.class);
I have many statefull forms in every page.
I'm now trying to handle the case when the session expires (to reproduce this scenario I delete or modify the jsessionid cookie).
After that I click a submit button in a page and I'd expect wicket to understand that the session has expired.
But the behaviour that I have is this:
the current page is reloaded but the pageparameters are 'null'
the url is rewritten using the package notation like:
localhost:8080/wicket/bookmarkable/com.test.pages.MyPage
So it looks like the url mapping is somehow lost.
I need to reload the same page with pageParameters information or show an info page that says something like click here to reload.
I've already tried to use:
getApplicationSettings().setPageExpiredErrorPage(HomePage.class);
but that didn't help.
Any help is appreciated. Thanks.
Looks like there is a bug in Wicket 6 which causes this issue: https://issues.apache.org/jira/browse/WICKET-5068
It is fixed in Wicket 7. For Wicket 6, there is a workaround: disable WICKET-4594 fix.
First add the following mapper:
public class BookmarkableMapperThatSavesPageParametersForListener extends BookmarkableMapper {
#Override
protected PageParameters getPageParametersForListener(PageInfo pageInfo, PageParameters pageParameters) {
return pageParameters;
}
}
Then use it to replace a built-in BookmarkableMapper in your Application#init() (this has to be added before any manipulations with the root mapper):
mount(new BookmarkableMapperThatSavesPageParametersForListener());
This approach works in our application and it does not seem to break anything.
More info: Wicket 6: empty PageParameters when recreating a page after expiration
You could ask your question in the wicket mailing list. What you are observing might be a bug. Please check PageParameters missing from re-created Page
Conceptually, it should be possible to submit the form normally even if you need an authenticated user session.
If the session is expired then you may be able to re-create a user session with a remember-me cookie. Wicket should re-construct the page with parameters, apply the form values and process the submit. In case where the page is stateful, there could be some complications that are possibly resolvable. If you find that your use case is not supported with stateful pages then you could file an issue and meanwhile use StatelessForm.

cakephp, session not working unless allow a cookie in browser

Using latest version of cakephp v2.3.3
I have a problem with my session variables when a browser doesn't allow cookies.
I pass variables from one controller to the other and this works perfect as long as the browser has cookies enabled. I have tried it with the Session helper in the controllers, but no effort, same problem.
How to fix this, is there a work around???
Cookies are required to keep track of the session ID, but you can manually get or set the session ID using $this->Session->id(). By adding the code below to the App Controllers' before filter you can set the session ID as a URL paramter like http://example.com/posts/view/1?session=qkv108c2pqeubcpeos1q7ekds3, for example.
if (!empty($this->request->query['session'])) {
$this->Session->id($this->request->query['session']);
}
The session ID is required for every request which means you have to include it in every link. I would suggest extending the HTML helpers' url and link methods to automatically add it.
Edit:
You should verify that $this->Session->read('Config.userAgent'); or $this->request->clientIp(); has not changed since the user was authenticated to prevent session hijacking. Thanks to thaJeztah for pointing this out.

ASP.NET MVC2 and Browser Caching

I have a web application that fetches a lot of content via ajax. For example when a user edits some data, the browser will send the changes using an ajax post and then do an ajax get to get fresh content and replace an existing div on the page with that content. This was working just find with MVC1, but in MVC2 I would get inconsistent results.
I've found that MVC1 by default included an Expires item in the response headers set to the current time, but in MVC2 the Expires header is missing. This is a problem with some browsers (IE8) actually using the cached version of the ajax get instead of the fresh version.
To deal with the problem I created a simple ActionFilterAttribute that sets the reponse cache to NoCache (see below), which works, but it seems kind of sillly to decorate every controller with this attribute. Is there a global way to set this for every controller?
Is this a bug in MVC2 and it really should be setting the expires on every ActionResult/view/page? Don't most MVC programs deal with data entry where stale data is a very bad thing?
Thanks
Dan
public class ResponseNoCachingAttribute : ActionFilterAttribute
{
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
base.OnResultExecuted(filterContext);
filterContext.HttpContext.Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
}
}
Have you tried adding the following attribute to your controller?
[OutputCache(Location = OutputCacheLocation.None)]

Resources