locked
URGENT: Rewritten URLs - transform into internal path and retrieve querystring RRS feed

  • Question

  • User-1389933028 posted

    Hi,

    I'm an average asp.net (C#, VS2010) developer with a concern about my accommodation site's URLs, I need them to be search engine friendly, yet internally, they need to be functional enough to provide the original querystrings generated by my code.

    I have a c# masterpage which I'm using to append querystring parameters (using Response.Redirect() according to SelectedIndexChanged events of it's dropdownlist controls - I did this so it would save me time rewriting the code for my child pages.  I need querystrings because I want to make it easy for customers to just type in the country: eg. www.internationalaccommodation.com/Brazil and instantly get information they need (since the website is dynamically driven by an SQL database).

    FIGURE 1: An example of my redirection code in SelectedIndexChanged event

    protected void CountryList_SelectedIndexChanged(object sender, EventArgs e)
        {
    
            SessionParameter CountryName = new SessionParameter();
            CountryName.Name = "CountryName";
            CountryName.Type = TypeCode.String;
            CountryName.SessionField = "Propid";
    
            //If dropdownlist value has been changed:
            // 1. Store in label
            // 2. Hide Country dropdownlist
            // 3. Show State/Area dropdownlist of places within a country that have properties
    
            if (CountryList.SelectedIndex != 0)
            {
                CountryLabel.Text = CountryList.SelectedItem.Text;
                Session["CountryName"] = CountryLabel.Text;
                //TopPropLView.DataSourceID = "OtherPropData";
                //TopPropLView.DataBind();
                CountryList.Visible = false;
                //CountryLabel.Visible = false;
                //TopPropLView.DataSource = null;
                //StateList.Visible = true;
    
                if (Request.Url.Query.Contains("?country=") == true) //replace querystring on each dropdownlist selection
                {
                    //Request.Url.Query.Replace("?country=1", "?country=8");
                    var nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
                    nameValues.Set("country", CountryLabel.Text);
                    string url = Request.Url.AbsolutePath;
                    string updatedQueryString = "?" + nameValues.ToString();
                    
                    Response.Redirect(url + updatedQueryString);
                }
                else
                {
                    Response.Redirect(Request.Url.AbsoluteUri + "?country=" + CountryLabel.Text);
                }
    
            }
            else if (CountryList.SelectedValue == "International")
            {
                TopPropLView.DataSourceID = "PropertyData";
                TopPropLView.DataBind(); //set Top properties to default datasource
                CountryList.Visible = true;
                CountryLabel.Visible = false;
                StateList.Visible = false;
            }
            
            
        }

    This is a screenshot of my cascading dropdowns - note: I'm not using AJAX enabled ones, I used plain <asp:dropdownlist /> which pass values from one to another using querystrings. Altogether, there are 4 dropdownlists: Country -> State (appears if country has states which have properties) -> Area (Cities) -> Property Types (shows property types resulted from previous selections)

    Below is code I use to check for querystrings within the URL which is posted back:

    protected void Page_Load(object sender, EventArgs e)
        {
            //var nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
    
            if (!IsPostBack) //check if the webpage is loaded for the first time.
            {
                ViewState["PreviousPage"] =
            Request.UrlReferrer;//Saves the Previous page url in ViewState
            }
    
               // ViewState["RefUrl"] = Request.UrlReferrer.ToString();
                //ViewState["PreviousPage"] = Request.UrlReferrer; //Saves the Previous page url in ViewState
            if ((Request.Url.Query.Contains("?country=") == true) && (Request.Url.Query.Contains("state=") == false) && (Request.Url.Query.Contains("area=") == false) && (Request.Url.Query.Contains("propertytype") == false)) //replace querystring on each dropdownlist selection
                {
                    StateData.SelectParameters["Country"].DefaultValue = Request.QueryString["country"];
                    //OtherPropData.SelectParameters["Country"].DefaultValue = Request.QueryString["country"];
                    //NewAreaData.SelectParameters["Country"].DefaultValue = Request.QueryString["country"];
                    TopPropLView.DataSourceID = "OtherPropData";
                    TopPropLView.DataBind();
                    CountryList.Visible = false;
                    //StateList.Visible = true;
                    int currentcount = StateList.Items.Count;
    
                    if ((StateList.Items.Count >= 2))
                    {
                        StateList.Visible = true;
                        
                    }
                    else
                    {
                        StateList.Visible = false;
                        AreaList.Visible = true;
                        
                    }
    
                }
            else if ((Request.Url.Query.Contains("?country=") == true) && (Request.Url.Query.Contains("state") == true) && (Request.Url.Query.Contains("area") == false) && (Request.Url.Query.Contains("propertytype") == false)) //replace querystring on each dropdownlist selection
                {
                    CountryList.Visible = false;
                    AreaData.SelectParameters["Country"].DefaultValue = Request.QueryString["country"];
                    AreaData.SelectParameters["State"].DefaultValue = Request.QueryString["state"];
                    //StateList.Visible = true;
                    if (StateList.Items.Count != 2)
                    {
                        StateList.Visible = true;
                        //AreaList.Visible = true;
                    }
                    else
                    {
                        StateList.Visible = false;
                        AreaList.Visible = true;
                    }
                }
            //etc...
        }


    Please could I have some advice as to the steps I should take in preparing this site for hosting, in regards to rewriting URLs while making sure they are functional enough to operate internally.

    Your help will certainly be most appreciated,

    BayVee

    Wednesday, July 4, 2012 1:24 AM

Answers

  • User-578657687 posted

    Hi,

    Not sure what you your requirement is exactly. I guess you are trying to implement the URL Rewriting. If I misunderstand your requirement, you can use IIS URL Rewriting Module:

    http://learn.iis.net/page.aspx/734/url-rewrite-module/

    And you also can try asp.net url rewrting:

    http://www.codeproject.com/Articles/2538/URL-Rewriting-with-ASP-NET

    And ASP.NET ROUTING:

    http://www.codeproject.com/Articles/37917/URL-rewriting-using-ASP-NET-routing

    If you aren't familar with IIS URL Rewrting Module, the asp.net url rewrting may be your consideration. The comparsion about routing and url rewrting please check below:

    ASP.NET routing differs from URL rewriting. URL rewriting processes incoming requests by actually changing the URL before it sends the request to the Web page. For example, an application that uses URL rewriting might change a URL from /Products/Widgets/ to /Products.aspx?id=4. Also, URL rewriting typically does not have an API for creating URLs that are based on your patterns. In URL rewriting, if you change a URL pattern, you must manually update all hyperlinks that contain the original URL.

    With ASP.NET routing, the URL is not changed when an incoming request is handled, because routing can extract values from the URL. When you have to create a URL, you pass parameter values into a method that generates the URL for you. To change the URL pattern, you change it in one location, and all the links that you create in the application that are based on that pattern will automatically use the new pattern.

     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, July 6, 2012 12:04 AM
  • User-578657687 posted

    My concern with this though is that after URL rewriting is that I may not be able to extract the querystring (usually written as ?Product=) because the URL is only showing the value of the Querystring.

    In an ASP.NET application that does not use routing, an incoming request for a URL typically maps to a physical file that handles the request, such as an .aspx file. For example, a request for http://server/application/Products.aspx?id=4 maps to a file that is named Products.aspx that contains code and markup for rendering a response to the browser. The Web page uses the query string value of id=4 to determine what type of content to display.

    In ASP.NET routing, you can define URL patterns that map to request-handler files, but that do not necessarily include the names of those files in the URL. In addition, you can include placeholders in a URL pattern so that variable data can be passed to the request handler without requiring a query string.

    For example, in the request for http://server/application/Products/show/beverages, the routing parser can pass the values Products, show, and beverages to the page handler. In this example, if the route is defined by using the URL pattern server/application/{area}/{action}/{category}, the page handler would receive a dictionary collection in which the value associated with the key area is Products, the value for the key action is show, and the value for the key category is beverages. In a request that is not managed by URL routing, the /Products/show/beverages fragment would be interpreted as the path of a file in the application.

    More information please check this walkthrough about asp.net routing:

    http://msdn.microsoft.com/en-us/library/dd329551.aspx

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 9, 2012 3:01 AM
  • User-1856974186 posted

    Rewriting is an internal process and doesn't necessarily impact what's actually in the address bar as opposed to the QueryString. So if you rewrite the path to include a query string, then that's what the target page will see - a request with a query string - but the address bar remains the same.

    Routing doesn't use query strings, but passes the data through in a RouteData object, so your target pages would need to be aware of that. Rewriting does use the querystring, so the third-party rewriting strategies should work fine without the target page being modified. You can also do the rewriting manually in global.asax. Eg:

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
      HttpContext context = HttpContext.Current;
      string opath = context.Request.Path;
      string path = opath.toLower();

      if (path.Contains("/product/"))
      {
        string product = GetProductFromPath(opath);
        HttpContext.Current.RewritePath("~/Product.aspx?product=" + product);
      }
    }

    In this case the RewritePath rewrites the internal path of the request, but this doesn't affect the URL in the browser.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, July 10, 2012 5:27 AM

All replies

  • User-578657687 posted

    Hi,

    Not sure what you your requirement is exactly. I guess you are trying to implement the URL Rewriting. If I misunderstand your requirement, you can use IIS URL Rewriting Module:

    http://learn.iis.net/page.aspx/734/url-rewrite-module/

    And you also can try asp.net url rewrting:

    http://www.codeproject.com/Articles/2538/URL-Rewriting-with-ASP-NET

    And ASP.NET ROUTING:

    http://www.codeproject.com/Articles/37917/URL-rewriting-using-ASP-NET-routing

    If you aren't familar with IIS URL Rewrting Module, the asp.net url rewrting may be your consideration. The comparsion about routing and url rewrting please check below:

    ASP.NET routing differs from URL rewriting. URL rewriting processes incoming requests by actually changing the URL before it sends the request to the Web page. For example, an application that uses URL rewriting might change a URL from /Products/Widgets/ to /Products.aspx?id=4. Also, URL rewriting typically does not have an API for creating URLs that are based on your patterns. In URL rewriting, if you change a URL pattern, you must manually update all hyperlinks that contain the original URL.

    With ASP.NET routing, the URL is not changed when an incoming request is handled, because routing can extract values from the URL. When you have to create a URL, you pass parameter values into a method that generates the URL for you. To change the URL pattern, you change it in one location, and all the links that you create in the application that are based on that pattern will automatically use the new pattern.

     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, July 6, 2012 12:04 AM
  • User-1389933028 posted

    Hi Mamba,

    Yes, I am looking at implementing URL rewriting for my application. Reason for doing this is that I want to mask the querystrings (e.g. ?Product=) from the user and just show the value of the Querystring (e.g. www.website.com/SomeProductName). My concern with this though is that after URL rewriting is that I may not be able to extract the querystring (usually written as ?Product=) because the URL is only showing the value of the Querystring.

    Friday, July 6, 2012 12:55 AM
  • User-578657687 posted

    My concern with this though is that after URL rewriting is that I may not be able to extract the querystring (usually written as ?Product=) because the URL is only showing the value of the Querystring.

    In an ASP.NET application that does not use routing, an incoming request for a URL typically maps to a physical file that handles the request, such as an .aspx file. For example, a request for http://server/application/Products.aspx?id=4 maps to a file that is named Products.aspx that contains code and markup for rendering a response to the browser. The Web page uses the query string value of id=4 to determine what type of content to display.

    In ASP.NET routing, you can define URL patterns that map to request-handler files, but that do not necessarily include the names of those files in the URL. In addition, you can include placeholders in a URL pattern so that variable data can be passed to the request handler without requiring a query string.

    For example, in the request for http://server/application/Products/show/beverages, the routing parser can pass the values Products, show, and beverages to the page handler. In this example, if the route is defined by using the URL pattern server/application/{area}/{action}/{category}, the page handler would receive a dictionary collection in which the value associated with the key area is Products, the value for the key action is show, and the value for the key category is beverages. In a request that is not managed by URL routing, the /Products/show/beverages fragment would be interpreted as the path of a file in the application.

    More information please check this walkthrough about asp.net routing:

    http://msdn.microsoft.com/en-us/library/dd329551.aspx

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 9, 2012 3:01 AM
  • User-1856974186 posted

    Rewriting is an internal process and doesn't necessarily impact what's actually in the address bar as opposed to the QueryString. So if you rewrite the path to include a query string, then that's what the target page will see - a request with a query string - but the address bar remains the same.

    Routing doesn't use query strings, but passes the data through in a RouteData object, so your target pages would need to be aware of that. Rewriting does use the querystring, so the third-party rewriting strategies should work fine without the target page being modified. You can also do the rewriting manually in global.asax. Eg:

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
      HttpContext context = HttpContext.Current;
      string opath = context.Request.Path;
      string path = opath.toLower();

      if (path.Contains("/product/"))
      {
        string product = GetProductFromPath(opath);
        HttpContext.Current.RewritePath("~/Product.aspx?product=" + product);
      }
    }

    In this case the RewritePath rewrites the internal path of the request, but this doesn't affect the URL in the browser.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, July 10, 2012 5:27 AM