How to send a session to another ASP.NET WebForm page? - c#

I have created an ASP.NET WebForm application. Let's say for example I have a string value and want to send it to another page in my app e.g.
string sValue = "information";
I then put this into a session as so:
Session["value"] = sValue;
I then want to navigate to another page in my web app so i use:
Response.Redirect("~/ViewInvoices.aspx");
However when I try to extract any information from the session it is null
string sValue = Session["value"]; <-is now null
Could anyone either spot the problem or even better offer a solution to make this work?

Use this for redirecting:
Response.Redirect("~/ViewInvoices.aspx", false);

Related

Is It possible to serialize the session object in ASP Classic? [duplicate]

We have a website in classic asp that we are slowly migrating to ASP.NET as necessary.
The problem of course is how classic asp and ASP.NET handle Sessions. After spending the last few hours researching the web, I found many articles, but not one that stood out over the others.
Is there a best practice for transferring session variables from and to classic asp and asp.net? Security is a must and any explanation with examples is much appreciated.
A simple bridge to pass a single session variable from classic asp to .net serverside (hiding your sessionvalue from the client), would be this:
On the ASP end: An asp page to output your session, call it e.g. asp2netbridge.asp
<%
'Make sure it can be only called from local server '
if (request.servervariables("LOCAL_ADDR") = request.servervariables("REMOTE_ADDR")) then
if (Request.QueryString("sessVar") <> "") then
response.write Session(Request.QueryString("sessVar"))
end if
end if
%>
On the .net end, a remote call to that asp page. :
private static string GetAspSession(string sessionValue)
{
HttpWebRequest _myRequest = (HttpWebRequest)WebRequest.Create(new Uri("http://yourdomain.com/asp2netbridge.asp?sessVar=" + sessionValue));
_myRequest.ContentType = "text/html";
_myRequest.Credentials = CredentialCache.DefaultCredentials;
if (_myRequest.CookieContainer == null)
_myRequest.CookieContainer = new CookieContainer();
foreach (string cookieKey in HttpContext.Current.Request.Cookies.Keys)
{
' it is absolutely necessary to pass the ASPSESSIONID cookie or you will start a new session ! '
if (cookieKey.StartsWith("ASPSESSIONID")) {
HttpCookie cookie = HttpContext.Current.Request.Cookies[cookieKey.ToString()];
_myRequest.CookieContainer.Add(new Cookie(cookie.Name, cookie.Value, cookie.Path, string.IsNullOrEmpty(cookie.Domain)
? HttpContext.Current.Request.Url.Host
: cookie.Domain));
}
}
try
{
HttpWebResponse _myWebResponse = (HttpWebResponse)_myRequest.GetResponse();
StreamReader sr = new StreamReader(_myWebResponse.GetResponseStream());
return sr.ReadToEnd();
}
catch (WebException we)
{
return we.Message;
}
}
I've used an ajax bridge (for want of a better term), specifically, a classic asp page that reads all session vars into a database with a guid, it then redirects to a .net page passing the guid in the querystring, the asp.net page reads from sql for the given guid and created those vars as sessions.
Eg, in classic asp (pseudocode code - just to give you an idea, use parameterised queries in yours etc):
'#### Create GUID
Dim GUID 'as string
GUID = CreateWindowsGUID() '#### Lots of methods on http://support.microsoft.com/kb/320375
'#### Save session to sql
For Each SessionVar In Session.Contents
db.execute("INSERT INTO SessionBridge (GUID, Key, Value) VALUES ('" & GUID & "', '" & SessionVar & "', '" & session(SessionVar) & "')")
Next
Then, in a .net page:
'#### Fetch GUID
Dim GUID as string = Request.QueryString("GUID")
session.clear
'#### Fetch from SQL
db.execute(RS, "SELECT * FROM SessionBridge WHERE GUID = '" & GUID & "'")
For Each db_row as datarow in RS.rows
Session(db_row("Key")) = db_row("Value")
Next
As i say, this is very rough pseudocode, but you can call the asp with a simple background ajax function, then call the .net page for the given GUID.
This has the advantage of not exposing all your vars and values to the client (as post methods do etc).
They use different sessions, so you'll need to devise some way of transferring the vars yourself. You could include them in cookies, or send them via HTTP POST (i.e. a form with hidden fields) to the asp.net side.
Alternatively, you could scrap using session storage and stick everything in a database for each user/session, then just pass a session key from classic ASP to ASP.NET via one of the above suggestions. I know this sounds like you're reinventing the wheel, but this might be one of those cases where you just can't get around it.
I have a website that does that exact action. The secret is to use an intermediate page with the asp function response.redirect
<%
client_id = session("client_id")
response.redirect "aspx_page.aspx?client_id=" & client_id
%>
This is an example to pull the classic asp session variable client_id and pass it to an aspx page. Your aspx page will need to process it from there.
This needs to be at the top of a classic asp page, with no HTML of any type above. IIS will process this on the server and redirect to the aspx page with the attached query string, without sending the data to the client machine. It's very fast.
In case anyone else stumbles here looking for some help, another possible option is to use cookies. The benefit of a cookie is that you can store reasonable amounts of data and then persist that data to your .Net application (or another web application). There are security risks with exposing a cookie since that data can be easily manipulated or faked. I would not send sensitive data in a cookie. Here the cookie is only storing a unique identifier that can be used to retrieve data from a table.
The approach:
Grab the session data you need from your classic asp page. Store
this data in a table along with a unique hash and a timestamp.
Store the value of the hash in a short-lived cookie.
Redirect to whatever page you need to go and read the hash in the cookie.
Check that the hash in the cookie hasn't expired in the database. If it is valid, send back the data you need to your page and then expire the hash so it can't be reused.
I used a SHA 256 hash that was a combination of the user's unique identifier, session ID, and current timestamp. The hash is valid for only a few minutes and is expired upon reading. The idea is to limit the window for an attacker who would need to guess a valid hash before it expired.

Remembering Session in iframe with ASP.NET WebForms

Strange behavior occured in an old WebForms app. I can't give you link, or big picture, I can only ask for specific detail, so maybe someone has an idea which way to explore.
App on the domain A embeds app on another domain B within iframe. (If it hosts the site on the same domain, then it's fine, the problem doesn't occur.)
domainA.com:
<iframe src="http://domainB.com/page1.aspx" />
page1.aspx writes a Session variable:
http://domainB.com/page1.aspx:
HttpContext.Current.Session["UTCOffset"] = utcOffset.ToString();
However, ASHX handler handler.ashx within that iframe can't read the Session variable value.
http://domainB.com/handler.ashx:
string utcOffset = Convert.ToString(HttpContext.Current.Session["UTCOffset"]);
utcOffset is empty string.
Have in mind, when this is not inside iframe, (e.g. request http://domainB.com/page1.aspx through browser) this works fine.
It also works fine if this is all hosted on the same domain.
Also it was working fine until recently, on most major browsers.
Did something change recently regarding Session policy within frames, due to CORS or something?
How do I fix this?
I solved it simply by using cookies. Tested it, it works fine.
So instead of the code in page1.aspx:
HttpCookie UTCOffset = new HttpCookie("UTCOffset");
UTCOffset.Values.Add("utcOffset", utcOffset.ToString());
UTCOffset.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(UTCOffset);
and in handler, instead of current code:
string utcOffset = string.Empty;
HttpCookie UTCOffset = HttpContext.Current.Request.Cookies["UTCOffset"];
if (UTCOffset != null && !string.IsNullOrEmpty(UTCOffset.Values["utcOffset"]))
{
utcOffset = UTCOffset.Values["utcOffset"].ToString();
}

Pulling external website URL parameters

Currently I have a MVC Registration page which is implemented in an external website.
My question is I need to now extract the previous website's querystring for a certain parameter and read it into my page to register a user into the designated group.
So the workflow looks as follows :
User hits the external website (example: www.test1.com/default.aspx?Code=123asd) with a code in the querystring
user selects Register Now and gets directed to my page.
How will I be able to read the previous querystring code into my MVC page? I do not have access to that website.
EDIT
I currently have a foreach statement which reads the current querystring but this is not pulling the previous request's querystring:
private static string getCode()
{
string nothing = null;
string[] queryStringParaArray = HttpContext.Current.Request.UrlReferrer.Query.Substring(1).Split('=');
if (queryStringParaArray.Length > 0)
{
foreach (var para in queryStringParaArray)
{
if (para.Contains("Code"))
return queryStringParaArray[2];
}
}
return nothing;
}
Have you tried HttpRequest.UrlReferrer property which contains URL of the client's previous request that linked to the current URL. This returns a Uri object and thus you can access the Query property to get the query string value of it.
HttpContext.Request.UrlReferrer
**SideNote: As already commented, there is no guarantee that the referred URL would be present and thus it could be null as well. So would suggest you to pass that query string information directly to your MVC controller while clicking on Register button.

How to retrieve site root url?

I need to get the url of the site so that I render a user control on only the main page. I need to check for http://foo.com, http://www.foo.com, and foo.com. I am a bit stumped as to how check for all 3. I tried the following which does not work.
string domainName = Request.Url.Host.ToString();
if (domainName == "http://nomorecocktails.com" | Request.Url.Host.Contains("default.aspx"))
{ //code to push user control to page
Also tried
var url = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + "/";
Any thoughts?
You need to check if the Request.Path property is equal to / or /Default.aspx or whatever your "main page" is. The domain name is completely irrelevant. What if I accessed your site via http://192.56.17.205/, and similarly, what if your server switched IP addresses? Your domain check would fail.
If you utilize the QueryString to display different content, you'll also need to check Request.QueryString.
Documentation for Request.Path:
http://msdn.microsoft.com/en-us/library/system.web.httprequest.path.aspx
Documentation for Request.QueryString:
http://msdn.microsoft.com/en-us/library/system.web.httprequest.querystring.aspx
If you need the user control to only appear on the main page (I'm assuming you mean home page), then add the code to call the user control to the code behind of that file.
If this code is stored in the master page, then you can reference it like:
Master.FindControl("UserControlID");
If you are only using the one web form (ie. just Default.aspx), then you can check that no relevant query strings are included in the URL, and display only if this is the case:
if (Request.QueryString["q"] == null){
//user control code
}
However if you are using this technique then I would recommend using multiple web forms using master pages in the future to structure your application better.
The ASP.NET website has some good tutorials on how to do this:
http://www.asp.net/web-forms/tutorials/master-pages

Remove QueryString Variable in c#

I am very beginner With Programming...(unfortunately)
I want to remove Any added QueryString To Address after i get the variables. for example:
www.websiteName.com/page.aspx?a=344&b=233
i will get a and b and after that i want my address to look like this:
(www.websiteName.com) .
"root location".
any help...
thanks.
var queryString = Request.QueryString;
// Handle querystring, then redirect to root
Response.Redirect("~/");
Response.End();
You will have to reload the page. When changing the URL, you are making another request to the server.
I wrote a blog on retrieving the URL of an ASP.Net application. Simply add the page name after the result.
This blog describes how to manipulate the query string to redirect to the same page with different (or no) parameters.
Why not just use
Request.UserHostName

Categories