Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to add credential to a URL string?

Tags:

c#

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.

like image 475
Maxime Joyal Avatar asked Dec 25 '22 03:12

Maxime Joyal


1 Answers

Use UriBuilder:

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

which generates:

http://u:[email protected]/
like image 177
Pippi Longstocking Avatar answered Jan 08 '23 19:01

Pippi Longstocking