[英]Proper way to add credential to a URL string?
简单的问题。 我有一个 URL,我需要添加用户名和密码才能输入凭据。
我想知道 C# 中是否有一种方法可以接收 URL 字符串和凭据并返回带有凭据的 URL。 我想完全按照我对这个函数做的事情,但是这个函数正在读取特定的字符串,最终可能会导致错误:(它只是添加了用户名和凭据)
url = url.Substring(0, url.IndexOf("/") + 2) + userName + ":" + password + "@" + url.Substring(url.IndexOf("/") + 2);
这种做法真的是静态的...我需要获取 URL 的最终字符串。
使用UriBuilder
:
var uri = new Uri("http://www.example.org");
var uriWithCred = new UriBuilder(uri) { UserName = "u", Password = "p" }.Uri;
它产生:
http://u:p@www.example.org/
归功于上面的答案,要处理 @、#、: 等字符,您需要对用户和密码进行 URL 编码:
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.