How to build a Url?

后端 未结 3 1632
情话喂你
情话喂你 2020-12-07 23:46

Are there any helper classes available in .NET to allow me to build a Url?

For example, if a user enters a string:

stackoverflow.com
<
相关标签:
3条回答
  • 2020-12-08 00:29

    You can use the UriBuilder class.

    var builder = new UriBuilder(url);
    builder.Port = 3333
    builder.Scheme = "https";
    
    var result = builder.Uri;
    
    0 讨论(0)
  • 2020-12-08 00:38

    To be valid a URI needs to have the scheme component. "server:8088" is not a valid URI. "http://server:8088" is. See https://tools.ietf.org/html/rfc3986

    0 讨论(0)
  • 2020-12-08 00:42

    If you need to ensure that some string coming as user input is valid url you could use the Uri.TryCreate method:

    Uri uri;
    string someUrl = ...
    if (!Uri.TryCreate(someUrl, UriKind.Absolute, out uri))
    {
        // the someUrl string did not contain a valid url 
        // inform your users about that
    }
    else
    {
        var request = WebRequest.Create(uri);
        // ... safely proceed with executing the request
    }
    

    Now if on the other hand you want to be building urls in .NET there's the UriBuilder class specifically designed for that purpose. Let's take an example. Suppose you wanted to build the following url: http://example.com/path?foo=bar&baz=bazinga#some_fragment where the bar and bazinga values are coming from the user:

    string foo = ... coming from user input
    string baz = ... coming from user input
    
    var uriBuilder = new UriBuilder("http://example.com/path");
    var parameters = HttpUtility.ParseQueryString(string.Empty);
    parameters["foo"] = foo;
    parameters["baz"] = baz;
    uriBuilder.Query = parameters.ToString();
    uriBuilder.Fragment = "some_fragment";
    
    Uri finalUrl = uriBuilder.Uri;
    var request = WebRequest.Create(finalUrl);
    ... safely proceed with executing the request
    
    0 讨论(0)
提交回复
热议问题