Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading query-string in asp.net without specifying any page name

How to read any strings in a aspx page.

example: http://foo.com/bike stand

I want to read/get the strings in a specified aspx page. expected page string is bike stand
expected page is getstring.aspx

Here i like to read the string and redirect to specified page.
Note: I like to do this in just ASP.Net (Not with MVC)

like image 690
Sensa Avatar asked Jan 24 '17 07:01

Sensa


People also ask

How do I pass query string?

To pass in parameter values, simply append them to the query string at the end of the base URL. In the above example, the view parameter script name is viewParameter1.


2 Answers

You can probably solve this using a Route. I have made a simple demo, that you can try out in just a couple of minutes. In the Global.asax.cs file, add this method:

void RegisterRoutes(RouteCollection routes)
{
    routes.MapPageRoute("Products",
        "Products/{product}", "~/getstring.aspx",
        false,
        new RouteValueDictionary { { "product", "NoneSelected" } }
    );
}

In the same file, in the already existing void Application_Start(object sender, EventArgs e) method, add RegisterRoutes(RouteTable.Routes);:

void Application_Start(object sender, EventArgs e)
{
    RegisterRoutes(RouteTable.Routes);
}

With this, you have configured a Route which will take a request like this:

http://foo.com/Products/bike%20stand

and map it to getstring.aspx. Note that I have url encoded the space in the url.

In getstring.aspx you can access the value ("bike stand") like this:

protected void Page_Load(object sender, EventArgs e)
{
    string routeValue = "";
    if (RouteData.Values.ContainsKey("product"))
        routeValue = RouteData.Values["product"].ToString();

    //routeValue now contains "bike stand"

    SelectedProduct.Text = routeValue;
}

I have set up the Route in this sample on the path "Products" beneath the application folder. I don't recommend that you setup your route directly under the application folder as in the question. You can do it though if you absolutely want to:

void RegisterRoutes(RouteCollection routes)
{
    routes.MapPageRoute("Products",
        "{product}", "~/getstring.aspx",
        false,
        new RouteValueDictionary { { "product", "NoneSelected" } }
    );
}
like image 194
user1429080 Avatar answered Oct 14 '22 12:10

user1429080


It may not the best way to fulfill your need but if you want to get the string part from URL you may use URI Segments.

HttpContext.Current.Request.Url.Segments.Select(x=>x.TrimEnd‌​('/')).Skip(2).ToArr‌​ay();

OR

new Uri("http://www.someurl.com/foo/xyz/index.htm#extra_text").Segments

Results: [ "/", "foo/", "xyz/", "index.html" ]

After reading string you can do whatever you want like redirection etc

like image 20
Bhupendra Shukla Avatar answered Oct 14 '22 11:10

Bhupendra Shukla