简体   繁体   中英

AbsolutePath with QueryString

I have the following code:

     if (Request.Url.AbsolutePath == "/Guidance.aspx")
        {
            if (Request.IsSecureConnection)
            {
              Reponse.Redirect("http://www.example.com/Guidance.aspx");
            }
            return;
        }

The thing is that Guidance can have a querystring with it. I like to then Redirect to the same page name and append the querystring. Haven't found a way to do this.

     if (Request.Url.AbsolutePath == "/Guidance.aspx?id='vid09'")
        {
            if (Request.IsSecureConnection)
            {
              Reponse.Redirect("http://www.example.com/Guidance.aspx?id='vid09'");
            }
            return;
        }

How can I simplify the code above to do it with any querystring that comes its way.

Use UriBuilder and replace parts you need. Something like:

var builder = new UriBuilder(Request.Url);
builder.Scheme = "http";
Reponse.Redirect(builder.ToString);
string myUrl = Request.RawUrl.toString();
if (myUrl.Contains("/Guidance.aspx")
    {
        if (Request.IsSecureConnection)
        {
          var queryString = myUrl.Substring(myUrl.IndexOf("?"));
          Reponse.Redirect("http://www.example.com/Guidance.aspx" + queryString);
        }
        return;
    }

Don't get fancy, the URI is already parsed for you (don't do it yourself with unreliable regular expressions). The Url property you're using is a System.Uri object. You may simply compare the scheme, host, and any HTTP segment you may need, then construct your redirection URI by adding only the query string component from the original URI. All you need is in the Uri class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM