Returning a value from a page - asp.net

How is it possible to return a value in an ASP.NET web page? I need to return the value "1". I'm not sure how to do that. Is it as simple as writing 1 in the content of the .aspx file, or do I need to do anything else?
That's the request that is given:
GET /kartclient/kartlogin.aspx HTTP/1.1. Accept: text/*

Since kartlogin.aspx seems to be a user-login page, then are you interested in passing userID + password to another page?
Still not sure what you are trying to achieve, but if its only passing data from one page to another, there are many ways, here are some quick ones you can try:
On kartlogin.aspx:
1. Query String Method Send/Post Value:
string name="xyz";
Response.Redirect("Page2.aspx?name= "+name);
2. Cookie Method Send/Post Value:
HttpCookie myCookie = new HttpCookie("name");
myCookie.Value="xyz";
Response.Cookies.Add(myCookie);
3. Session Method Save Value:
Session["name"] = "xyz";
On Page2.aspx:
1. Query String Method Get Value:
string name = Response.QueryString.GetValue(" name ");
Response.Write(name);
2. Cookie Method Get Value:
string name = Request.Cookies('name');
Response.Write(name);
3. Session Method Get Value:
string name = Session["name"].ToString();
Response.Write(name);
You should take a look at:
How to: Pass Values Between ASP.NET Web Pages
Stackoverflow: How can I pass values from one form to another in Asp.net
Stackoverflow: When to use Request.Cookies over Response.Cookies?
Eight Different Ways to Transfer Data from One Page to Another Page

Related

Accessing the query string value using ASP.NET

I have been trying to find the question to my answer but I'm unable to and finally I'm here. What I want to do is access the value passed to a webpage (GET, POST request) using asp.net. To be more clear, for example:
URL: http://www.foobar.com/SaleVoucher.aspx?sr=34
Using asp.net I want to get the sr value i.e 34.
I'm from the background of C# and new to ASP.NET and don't know much about ASP.NET.
Thanx.
Can you refer to this QueryString
Here he says how to access the query string using:
Request.Url.Query
That is not called a Header, but the Query String.
the object document.location.search will contain that and the javascript to get any query string value based on the key would be something like:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
code from other question: https://stackoverflow.com/a/901144/28004

Http.Page.Request[" "] not returning correct values

Situation:-
There is a Home.aspx page, which can be opened by a unique user ("userName" variable).
This page has a popup window control name 'alertWindow'.
In the pageLoad event of Home.aspx.cs, Welcome.aspx page is opened in the 'alertWindow' using NavigateUrl property.
The querystring passed to Welcome.aspx page contains a parameter "UserName" and this parameter is set to the logged in user's name ("userName" variable).
Now when the code execution comes to Welcome.aspx.cs page, "Request["UserName"]" is used to get\retrieve the current "userName" paramerter existing in the query string.
Issue:-
When a logged-in user's name has space or other non-usual characters, then "Request["UserName"].ToString()" doesn't retrieve the actual and correct value.
For Ex. if the logged in "userName" = "A&T Telecom", then "Request["UserName"].ToString() retrieves only "A" and nothing else.
But if the userName string is a proper value like "micheal", then "Request["UserName"].ToString() retrieves only "Micheal" correctly
Requirement:-
Please provide a way so that I get the correct value from Request["UserName"] for any kind of "userName" string value.
Home.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (user is valid)
alertWindow.NavigateUrl = "Welcome.aspx?userName=" + currentUser.ToString();
}
Welcome.aspx.cs:-
currentUserName = Request["userName"].ToString();
This is logical because you do not Encode your url. Try this:
alertWindow.NavigateUrl = "Welcome.aspx?userName=" + Server.UrlEncode(currentUser.ToString());
To say few more, they are some special characters that used on the URL, like the
: / # ? & # % + (and the space).
All that characters must be encode to a different format, so the url will not break, the UrlEncode do exactly that.
Two notes.
I select the Server to call the UrlEncode because is not depend from the Request, and you can use it inside a thread, or any function that is not called from the Page.
The Request.QueryString make UrlDecode when you use it. To get the encode url you call the Request.RawUrl
You cannot add white spaces within your url, it needs encoding so :
//uses HttpUtility.UrlEncode internally
Server.UrlEncode("something with spaces");
or
HttpUtility.UrlEncode("something with spaces");

Asp.net pass value from txtbox to an another page

This the end of my code
...
If lblErrMsg.Text = "" Then
Response.Redirect("UserPage.aspx")
End If
I want to pass the value of txtUser(I create It in the current page...) to the UserPage.aspx.
Thank's for helping me ...
This is in VB.net not in c# Please
C# Version
1) Use querystring
Response.Redirect("user.aspx?val="+txtBox.Text);
and in userp.aspx.cs,
string strVal=Request.QueryString["val"];
2)Use Session
Setting session in first page before redirecting
Session["val]=txtBox.Text;
Response.Redirect("user.aspx");
and in user.aspx.cs
String strVal=(string) Session["val"];
EDIT :VB.NET VERSION
1) Use Querystring
Response.Redirect("user.aspx?val=" + txtBox.Text)
and in user.aspx.vb
Dim strVal As String = Request.QueryString("val")
2)Use Session
Setting Session in firstpage
Session("val")=txtBox.Text
Response.Redirect("user.aspx")
and in user.aspx.vb.
Dim strVal As String = DirectCast(Session("val"), String)
You can pass it in the query string, like this:
Response.Redirect("UserPage.aspx?user=" + HttpUtility.UrlEncode(txtUser.Text));
And then retrieve it via:
string user = Request.QueryString["user"];
If you're worried about users messing with a query string (be sure to validate it), you could also store a Session variable before doing the redirect.
warning: this is a gross but easy solution
Session("myTextbox")= txtUser.Text
this will persist the value so on the page_load of the next page you can say
txtUser.Text=Session("myTextBox")
What are you passing form page to page? Is it a list of things. You could have an object with different properties and could then pass it through a session. If you have multiple pages I would suggest doing this if you could end up reusing it else where. Passing it through the url, you would then need to validate it, because if someone types the url with the correct information or something that is being directly input into a database they could cause problems and/or unexpected results.

redirecting pages using session

i'm new to ASP.NET,so plz b patient :D
i want to redirect one of my pages to the other one,and i keep the username!
i tried to use session.add and session[],but when i want to insert the username inside the brackets,it says use must int!!!but i thought i should use session["username"]
i used another way(request.querystring[]),but both have problems
here is my code
//first solution
string username="asal";
session.Add(username,username);
Response.Redirect("~/Doctor/DoctorsMainPage.aspx");
//in the other page
Label1.Text= Session["username"].ToString();//this one says use int?!
//i used this one instead of it
Label1.Text= Session[0].ToString();//with this one i get the username in other page,but one i want to pass another string like "id" with session,I can not!
//the second solution
string username="asal";
Response.Redirect("~/Doctor/DoctorsMainPage.aspx?username");
Label1.Text = Request.QueryString["username"];//this one redirect to doctors main page but set the value of username to "" !
session.Add(string, string) where the first string is the name of the variable and the second is the value.
You are adding the value twice.
//first solution
string username="asal";
session.Add("username",username); <-- this is your problem
Response.Redirect("~/Doctor/DoctorsMainPage.aspx");
//in the other page
Label1.Text= Session["username"].ToString();
Now, as for
//the second solution
string username="asal";
Response.Redirect("~/Doctor/DoctorsMainPage.aspx?username");
Label1.Text = Request.QueryString["username"];//this one redirect to doctors main page but set the value of username to "" !
In this case you're creating a url "~/Doctor/DoctorsMainPage.aspx?username"
Ok - so what is username? The code is looking for a param in the query string named username but it's not finding a value.
You need:
Response.Redirect("~/Doctor/DoctorsMainPage.aspx?username="+username);
That will give you "~/Doctor/DoctorsMainPage.aspx?username=asal"
string username = "asal";
Session["username"] = username;
Response.Redirect("~/Doctor/DoctorsMainPage.aspx");
//Other page
Label1.Text = Session["username"].ToString().Trim();
You have to add the session like..
session.Add("username",username); instead session.Add(username,username);
And then you can access the value like..Label1.Text= (String)Session["username"];
Check out this article related to the session State ASP.NET Session State Overview that will help you to understand Session State management.
Seconly querystring should be like, as you have not passing your string parameter and it should be like...
Response.Redirect("~/Doctor/DoctorsMainPage.aspx?username=" + username);

How to protect from tampering of query string?

Hii,
I have a query string like "http://project/page1.aspx?userID=5". The operation won't be performed, if the 'userID' parameter changed manually. How it is possible?
Hii all, thank you for your assistance... and i got some difference sort of solution from some other sites. i don't know that the best solution. that is to encode the value using an encryption and decryption algorithm... The sample code has been written like this...
<a href='Page1.aspx?UserID=<%= HttpUtility.UrlEncode(TamperProofStringEncode("5","F44fggjj")) %>'>
Click Here</a> <!--Created one anchor tag and call the function for TamperProofStringEncode-->
private string TamperProofStringEncode(string value, string key)
{
System.Security.Cryptography.MACTripleDES mac3des = new System.Security.Cryptography.MACTripleDES();
System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
mac3des.Key = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(key));
return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(value)) + "-" + Convert.ToBase64String(mac3des.ComputeHash(System.Text.Encoding.UTF8.GetBytes(value)));
}
In the page load of 'Page1' call the decode algorithm to decode the query string
try
{
string DataString = TamperProofStringDecode(Request.QueryString["UserID"], "F44fggjj");
Response.Write(DataString);
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
private string TamperProofStringDecode(string value, string key)
{
string dataValue = "";
string calcHash = "";
string storedHash = "";
System.Security.Cryptography.MACTripleDES mac3des = new System.Security.Cryptography.MACTripleDES();
System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
mac3des.Key = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(key));
try
{
dataValue = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(value.Split('-')[0]));
storedHash = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(value.Split('-')[1]));
calcHash = System.Text.Encoding.UTF8.GetString(mac3des.ComputeHash(System.Text.Encoding.UTF8.GetBytes(dataValue)));
if (storedHash != calcHash)
{
//'Data was corrupted
throw new ArgumentException("Hash value does not match");
// 'This error is immediately caught below
}
}
catch (Exception ex)
{
throw new ArgumentException("Invalid TamperProofString");
}
return dataValue;
}
It sounds like a strange requirement. Are you trying to implement some sort of home-grown security? If it's so, you really shouldn't.
Anyway, one way you could do it would be to take the entire url http://project/page1.aspx?userID=5 and calculate its md5 sum. Then you append the md5 sum to the final url, such as http://project/page1.aspx?userID=5&checksum=YOURCALCULATEDMD5SUM. Then in page1.aspx you will have to validate that the checksum parameter is correct.
However, this approach is quite naïve and it would not necesarily take very long for anyone to figure out the algorithm you have used. If they did they could "easily" change the userid and calculate an md5 sum themselves. A more robust approach would be one where the checksum was encrypted by a key that only you had access to. But again I have to question your motive for wanting to do this, because other security solutions exist that are much better.
Here is another option that I found incredibly useful for my requirements:
4 Guys From Rolla - Passing Tamper-Proof QueryString Parameters
You can't.
Anything in the HTTP request (including URL, query string, cookies, ...) is under the control of the client and is easy to fake.
This is why it is important to whitelist valid content, because the client can arbitrarily add anything it likes in addition to what you you prompt to receive.
My favourite is the following. It uses a HTTPmodule to transparently encode and decode the Querystring with the explicit purpose of preventing tamperring of the querystring.
http://www.mvps.org/emorcillo/en/code/aspnet/qse.shtml
It is perfect when Session is not an option!
You can't tell whether it has been changed manually. If you use query strings then you hyave to make sure that it doesn't matter if it is changed. e.g. if you are using it to show a user their account details, you need to check wether the selected user, is the current user and show an error message instead of user data if it is not.
If the user is allowed to change record 5, but not record 7 for example, this has to be enforced server-side. To do this you need to be able to identify the user, by requiring a login, and giving them a unique session key that is stored in their browser cookie, or as another parameter in the url query string.
There are abundant packages/modules/libraries in man languages for dealing with authentication and sessions in a sensible way - roll you own at your own peril :)
Well - it depends :)
One possibility is to put the userID into a session variable. So the user cannot see or edit the value.
If you have other means to detect if the value is invalid (i.e. does not exist or cannot be for that user (who you can identify through some other way) or the like) you might get away with validating the input yourself in code behind.
But as you probably know you cannot prevent the user changing the query string.

Resources