ASP.NET: URI handling

后端 未结 6 2071
暗喜
暗喜 2021-01-06 05:53

I\'m writing a method which, let\'s say, given 1 and hello should return http://something.com/?something=1&hello=en.

I

6条回答
  •  抹茶落季
    2021-01-06 06:25

    Edited to correct massively incorrect code

    Based on this answer to a similar question you could easily do something like:

    UriBuilder ub = new UriBuilder();
    
    // You might want to take more care here, and set the host, scheme and port too
    ub.Path = ResolveUrl("~/hello.aspx"); // Assumes we're on a page or control.
    
    // Using var gets around internal nature of HttpValueCollection
    var coll = HttpUtility.ParseQueryString(string.Empty);
    
    coll["something"] = "1";
    coll["hello"] = "en";
    
    ub.Query = coll.ToString();
    return ub.ToString();
    // This returned the following on the VS development server:
    // http://localhost/Hello.aspx?something=1&hello=en
    

    This will also urlencode the collection, so:

    coll["Something"] = "1";
    coll["hello"] = "en&that";
    

    Will output:

    Something=1&hello=en%26that 
    

提交回复
热议问题