Get url parameters from a string in .NET

前端 未结 13 1778
一个人的身影
一个人的身影 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: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¶m2=bad" )
    

    My workaround:

    string RawUrl = "http://www.example.com?param1=good¶m2=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" );`
    

提交回复
热议问题