簡體   English   中英

將憑據添加到 URL 字符串的正確方法?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM