Microsoft.Security.Application.Encoder.UrlPathEncode有什麼作用?

c# html-agility-pack

我找到一個使用HTMLAgilityPack的HTML清理程序的精彩示例 。在代碼中,使用Microsoft.Security.Application.Encoder類:

// AntiXss
a.Value = Microsoft.Security.Application.Encoder.UrlPathEncode(a.Value);

我找不到包含這個類的程序集,我寧願在我的項目中沒有另一個依賴項,並且清理程序在沒有這一行的情況下工作。但是,刪除此調用可能會在代碼中留下安全漏洞。

為了決定是否反對使用這個程序集,我想知道: 這個方法實際上做了什麼?

一般承認的答案

您可以查看源代碼

從方法的源代碼

/// <summary>
/// URL-encodes the path section of a URL string and returns the encoded string.
/// </summary>
/// <param name="input">The text to URL path encode</param>
/// <returns>The URL path encoded text.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage(
    "Microsoft.Design",
    "CA1055:UriReturnValuesShouldNotBeStrings",
    Justification = "This does not return a full URL so the return type can be a string.")]
public static string UrlPathEncode(string input)
{
    if (string.IsNullOrEmpty(input)) 
    { 
        return input; 
    } 

    // DevDiv #211105: We should make the UrlPathEncode method encode only the path portion of URLs. 
    string schemeAndAuthority; 
    string path; 
    string queryAndFragment; 
    bool validUrl = UriUtil.TrySplitUriForPathEncode(input, out schemeAndAuthority, out path, out queryAndFragment);

    if (!validUrl) 
    { 
        // treat as a relative URL, so we might still need to chop off the query / fragment components 
        schemeAndAuthority = null; 
        UriUtil.ExtractQueryAndFragment(input, out path, out queryAndFragment); 
    } 

    return schemeAndAuthority + HtmlParameterEncoder.UrlPathEncode(path, Encoding.UTF8) + queryAndFragment; 
}

在編碼uri時,您將不得不深入挖掘所有移動部件。通常我會建議查看單元測試以查看組件的預期,但乍一看沒有對Encoder類進行測試:(



Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow