简体   繁体   中英

Proper way to add credential to a URL string?

Simple problem. I have a URL, and I need to add the username and password to enter credentials.

I wanted to know if there is a method in C# which would receive the URL string and the credentials and return the URL with credentials in it. I'd like to do exactly what I do with this function, but this function is reading specific strings and may eventually cause errors: (it just add the username and the credentials)

url = url.Substring(0, url.IndexOf("/") + 2) + userName + ":" + password + "@" + url.Substring(url.IndexOf("/") + 2);

This way of doing is really static... I need to obtain the final string of the URL.

Use UriBuilder :

var uri = new Uri("http://www.example.org");
var uriWithCred = new UriBuilder(uri) { UserName = "u", Password = "p" }.Uri;

which generates:

http://u:p@www.example.org/

Credits to the answer above, to handle the @, #, :, etc characters you'll need to URL encode the user and the password:

  public static string CreateProtectedURL(string url, string username, string password)
    {
       
        var uri_protected= (new UriBuilder( new Uri(url)) { UserName = HttpUtility.UrlEncode(username), Password = HttpUtility.UrlEncode(password) }.Uri);

        return uri_protected.AbsoluteUri.ToString(); //will work in browser

       // return HttpUtility.UrlDecode(uri_protected.AbsoluteUri); //will not work in browser, you will get the normal url with user and pass 
    }

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