简体   繁体   English

将凭据添加到 URL 字符串的正确方法?

[英]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.我有一个 URL,我需要添加用户名和密码才能输入凭据。

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.我想知道 C# 中是否有一种方法可以接收 URL 字符串和凭据并返回带有凭据的 URL。 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.这种做法真的是静态的...我需要获取 URL 的最终字符串。

Use UriBuilder :使用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:归功于上面的答案,要处理 @、#、: 等字符,您需要对用户和密码进行 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM