Get url parameters from a string in .NET

前端 未结 13 1662
一个人的身影
一个人的身影 2020-11-22 11:38

I\'ve got a string in .NET which is actually a url. I want an easy way to get the value from a particular parameter.

Normally, I\'d just use Request.Params[

相关标签:
13条回答
  • 2020-11-22 12:00

    Use .NET Reflector to view the FillFromString method of System.Web.HttpValueCollection. That gives you the code that ASP.NET is using to fill the Request.QueryString collection.

    0 讨论(0)
  • 2020-11-22 12:01

    Use static ParseQueryString method of System.Web.HttpUtility class that returns NameValueCollection.

    Uri myUri = new Uri("http://www.example.com?param1=good&param2=bad");
    string param1 = HttpUtility.ParseQueryString(myUri.Query).Get("param1");
    

    Check documentation at http://msdn.microsoft.com/en-us/library/ms150046.aspx

    0 讨论(0)
  • 2020-11-22 12:02

    @Andrew and @CZFox

    I had the same bug and found the cause to be that parameter one is in fact: http://www.example.com?param1 and not param1 which is what one would expect.

    By removing all characters before and including the question mark fixes this problem. So in essence the HttpUtility.ParseQueryString function only requires a valid query string parameter containing only characters after the question mark as in:

    HttpUtility.ParseQueryString ( "param1=good&param2=bad" )
    

    My workaround:

    string RawUrl = "http://www.example.com?param1=good&param2=bad";
    int index = RawUrl.IndexOf ( "?" );
    if ( index > 0 )
        RawUrl = RawUrl.Substring ( index ).Remove ( 0, 1 );
    
    Uri myUri = new Uri( RawUrl, UriKind.RelativeOrAbsolute);
    string param1 = HttpUtility.ParseQueryString( myUri.Query ).Get( "param1" );`
    
    0 讨论(0)
  • 2020-11-22 12:02

    This is actually very simple, and that worked for me :)

            if (id == "DK")
            {
                string longurl = "selectServer.aspx?country=";
                var uriBuilder = new UriBuilder(longurl);
                var query = HttpUtility.ParseQueryString(uriBuilder.Query);
                query["country"] = "DK";
    
                uriBuilder.Query = query.ToString();
                longurl = uriBuilder.ToString();
            } 
    
    0 讨论(0)
  • 2020-11-22 12:04

    This is probably what you want

    var uri = new Uri("http://domain.test/Default.aspx?var1=true&var2=test&var3=3");
    var query = HttpUtility.ParseQueryString(uri.Query);
    
    var var2 = query.Get("var2");
    
    0 讨论(0)
  • 2020-11-22 12:05
    HttpContext.Current.Request.QueryString.Get("id");
    
    0 讨论(0)
提交回复
热议问题