C# Microsoft.Security.Application.Encoder.UrlPathEncode做什么?

C# Microsoft.Security.Application.Encoder.UrlPathEncode做什么?,c#,html-agility-pack,C#,Html Agility Pack,我发现了一个使用HTMLAgilityPack的HTML消毒剂。在代码中,使用了Microsoft.Security.Application.Encoder类: // AntiXss a.Value = Microsoft.Security.Application.Encoder.UrlPathEncode(a.Value); 我找不到包含此类的程序集,我更希望在我的项目中没有另一个依赖项,并且消毒剂可以在没有这一行的情况下工作。但是,删除此呼叫可能会在代码中留下安全漏洞 为了决定是否使用此程

我发现了一个使用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; 
}
//
///URL对URL字符串的路径部分进行编码并返回编码的字符串。
/// 
///文本到URL路径编码
///URL路径是经过编码的文本。
[System.Diagnostics.CodeAnalysis.SuppressMessage(
“Microsoft.Design”,
“CA1055:UriReturnValues不应为Bestrings”,
justion=“这不会返回完整的URL,因此返回类型可以是字符串。”)]
公共静态字符串UrlPathEncode(字符串输入)
{
if(string.IsNullOrEmpty(输入))
{ 
返回输入;
} 
//DevDiv#211105:我们应该让UrlPathEncode方法只对URL的路径部分进行编码。
字符串模式权限;
字符串路径;
字符串查询片段;
bool validull=UriUtil.TrySplitUriForPathEncode(输入、输出模式权限、输出路径、输出查询和片段);
如果(!validul)
{ 
//将其视为相对URL,因此我们可能仍然需要切掉查询/片段组件
schemeAndAuthority=null;
提取查询片段(输入、输出路径、输出查询片段);
} 
返回schemeAndAuthority+HtmlParameterEncoder.UrlPathEncode(path,Encoding.UTF8)+queryAndFragment;
}

您必须更深入地了解uri编码中的所有活动部分。通常我会建议查看单元测试以了解组件的预期内容,但乍一看,
Encoder
类上没有测试:(

类似于maybe(参见本文末尾的示例)。我认为这可以用于清理任何包含url的src/href类型属性(例如,使用
href='javascript:badthings()'
可能会劫持xss)