Asp.Net Query String - c#

I am using Querystring to pass values from one page to other. I am tring to implement encoding and decoding using the Server.UrlDecode and urlEncode.
Query string returns a null value, but I can check the values are been sent in URL.
The two pages are:
QueryString.aspx
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string id = "1";
string name = "aaaa";
string url = string.Format("QueryStringValuesTransfer.aspx?{0}&{1}", Server.UrlEncode(id), Server.UrlEncode(name));
Response.Redirect(url);
}
;;
In another page :
QueryStringValuesTransfer.aspx:
public partial class QueryStringValuesTransfer : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string id1 = Server.UrlDecode(Request.QueryString["id"]);
string name1 = Server.UrlDecode(Request.QueryString["name"]);
Response.Write(id1 + name1);
}
}
I am get null values in the id1 and name1.
Any help please..

Change this line:
string url = string.Format("QueryStringValuesTransfer.aspx?id={0}&name={1}", Server.UrlEncode(id), Server.UrlEncode(name));

Right now you are only setting the values in the querystring, you need to assign them names so you can grab them again:
string url = string.Format("QueryStringValuesTransfer.aspx?id={0}&name={1}", Server.UrlEncode(id), Server.UrlEncode(name));

That's because your query string should be something like
MyPage.aspx?id=xxx&name=yyy
You are not passing the values, only the names...

string url = string.Format("QueryStringValuesTransfer.aspx?{0}&{1}", Server.UrlEncode(id), Server.UrlEncode(name));
Should be:
string url = string.Format("QueryStringValuesTransfer.aspx?id={0}&name={1}", Server.UrlEncode(id), Server.UrlEncode(name));

You aren't specifying a name for the values. You need:
string url = string.Format("QueryStringValuesTransfer.aspx?id={0}&name={1}", Server.UrlEncode(id), Server.UrlEncode(name));

When constructing the URL in the first page you should do this:
string url = string.Format("QueryStringValuesTransfer.aspx?id={0}&name={1}", Server.UrlEncode(id), Server.UrlEncode(name));
The query string consists of key-value pairs, you should provide the keys.

Related

Decrypt Querystring Parameters and Map it to controller

I have One conroller method like
public ViewResult MyMethod(long id, string pId)
{
}
I have one query string like
?'id=' + 10 + '&pId=' + 15
I want to encrypt it using some encryption algorithm after that i got query sting in some format like
gaiSXZyTAq6Z0a5TzsrdG2LjIj0moe2m4D0qQiG7zuQ=
I am decrypting it from Global.asax in begin Request, Able to decrypt and setting Query string All Keys but controller not able to get its parameter value
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(Convert.ToString(Request.QueryString)))
{
var newQueryString = SecurityEncryption.DecryptionValue(HttpUtility.UrlDecode(Convert.ToString(Request.QueryString)).Replace(" ", "+"));
Request.QueryString.AllKeys[0] = newQueryString;
}
}
I want that Controller Method will get its Parameter values,How can I achieve this?
Please any one can help me.
I found sollution I decrypt my base controller
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var queryStringQ = Server.UrlDecode(filterContext.HttpContext.Request.QueryString["q"]);
if (!string.IsNullOrEmpty(queryStringQ))
{
// Decrypt query string value
var queryParams = DecryptionMethod(queryStringQ);
}
}

Fast method to change aspx extension

I use this way to rewite requested URL that have abc extension to aspx extension(found in SO):
void Application_BeginRequest(object sender, EventArgs e)
{
String fullOrigionalpath = Request.Url.ToString();
String[] sElements = fullOrigionalpath.Split('/');
String[] sFilePath = sElements[sElements.Length - 1].Split('.');
if (fullOrigionalpath.Contains(".abc") )
if (!string.IsNullOrEmpty(sFilePath[0].Trim()))
Context.RewritePath(sFilePath[0] + ".aspx");
}
but it seems this way is too slow. Can you say me How can I do this in web.config or other fast way?
Use Path.ChangeExtension. Don't Invent the wheel.
string aspxPath = Path.ChangeExtension(fullOrigionalpath, "aspx");

How to receive values passed to ASP.NET page with HTTP GET?

I'm trying to receive the values passed from other non aspx page to my asp.net page with C# via HTTP GET with Parameters. Would it be fine if I fetch the values with Request.QueryString in Page Load event?
Please advice.
Here's what I've done so far.
protected void Page_Load(object sender, EventArgs e)
{
//fetch query from url
string queryTimeStamp = Request.QueryString["t"];
Int64 queryCallerID = Convert.ToInt64(Request.QueryString["s"]);
int querySMSGateway = Convert.ToInt32(Request.QueryString["d"]);
string querySMSMessage = Request.QueryString["m"];
//Do other processings
}
you can get the value in Request.QueryString or Request.Form collection
Below is the better way to go, which will handle unexpected exception, thanks:
string queryTimeStamp = Request.QueryString["t"];
Int64 queryCallerID;
Int64.TryParse(Request.QueryString["s"] == string.Empty ? "0" : Request.QueryString["s"], out queryCallerID);
int querySMSGateway;
Int32.TryParse(Request.QueryString["d"] == string.Empty ? "0" : Request.QueryString["d"], out querySMSGateway);
string querySMSMessage = Request.QueryString["m"];

storing session id as a string and casting it back to GUID

I´m trying to use session to store a value (id). The problem is that I have to store it as a string. When trying to use the instance of the id I get the error:
Exception Details: System.InvalidCastException: Specified cast is not valid.
Source Error:
Line 156:
Line 157: Nemanet_Navigation newFile = new Nemanet_Navigation();
Line 158: newFile.Nav_pID = (Guid)Session["id"];
Line 159:
Line 160:
This is where I get the id and that seems to work fine. Session["id"] gets the value.
public void treeview_Navigation_SelectedNodeChanged(object sender, EventArgs e)
{
TreeNode node = treeview_Navigation.FindNode(treeview_Navigation.SelectedNode.ValuePath);
NavTreeNode nNode = node as NavTreeNode;
Session["id"]=((TreeView)sender).SelectedValue.ToString();
}
But this code does not seem to work. I get the error mentioned above.
protected void Button1_Click(object sender, EventArgs e)
{
Nemanet_Navigation newFile = new Nemanet_Navigation();
newFile.Nav_pID = (Guid)Session["id"];
}
Use Guid.Parse
protected void Button1_Click(object sender, EventArgs e)
{
Nemanet_Navigation newFile = new Nemanet_Navigation();
newFile.Nav_pID = Guid.Parse(Session["id"] as string);
}
Try using:
newFile.Nav_pID = new Guid(Session["id"].ToString());
You are converting GUID to string before saving it in session collection. But when you are retrieving it, you are trying to cast it in GUID which is invalid. String and GUID are not compatible types. Either save it as GUID or convert it into string (like you are doing) when saving and use GUID constructor that takes string to reform GUID instance.
You can do it like this:
Session["id"]=((TreeView)sender).SelectedValue.ToString();
and then retrieve it from session like:
newFile.Nav_pID = new Guid((string)Session["id"]);
By default the SessionID created by either aspx is not a GUID. You can created your own data type session id value. e.g :
HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie.Expires = DateTime.Now.AddMinutes(1.0);
myCookie.Value = g1.ToString();

Getting only the Referrer page not complete address in .NET

I am using C#. Below is my sample code.
private void Page_Load(object sender, System.EventArgs e)
{
string str = Request.UrlReferrer.ToString();
Label1.Text = str;
}
The result in Label1.Text is http://localhost:82/data/WebForm1.aspx.
Now I want the result "WebForm1.aspx" in Label1.Text
can you please help me?
Thanks.
If you want only the part after the last / in the URL, calling the System.IO.Path.GetFileName() method on the Uri.LocalPath should do the trick:
System.IO.Path.GetFileName(Request.UrlReferrer.LocalPath);
If you want the output to keep query string information from the URI, use the PathAndQuery property:
System.IO.Path.GetFileName(Request.UrlReferrer.PathAndQuery);
Try the LocalPath property on the UrlReferrer:
Label1.Text = Request.UrlReferrer.LocalPath;
It should provide you with just the filename.
Edit: this seems to also include the path, so only works for root.
In which case, you're better off just using Substring():
string str = Request.UrlReferrer.ToString();
Label1.Text = str.Substring(str.LastIndexOf('/')+1);

Categories