从文件读取时向 XmlResolver 提供身份验证凭据

当解析包含要读取的 XML 数据的文件的 URL 时,文件可能有一个受限制的访问策略。 如果需要身份验证才能访问网络资源,请使用 Credentials 属性指定必要的凭据。 如果未设置 Credentials 属性,凭据将设置为 null。

例如,假定在从 Web 请求数据时因身份验证目的而需要凭据。 如果 Web 虚拟目录允许匿名访问,则不需要为匿名访问设置该属性。 然而,如果该目录不允许匿名访问,那么您就需要提供凭据。 以下示例创建一个 XmlReader,使用具有默认凭据的 XmlUrlResolver 访问 https://localhost/bookstore/inventory.xml 站点。

' Create a resolver with default credentials.
Dim resolver as XmlUrlResolver = new XmlUrlResolver()
resolver.Credentials = System.Net.CredentialCache.DefaultCredentials

' Set the reader settings object to use the resolver.
settings.XmlResolver = resolver

' Create the XmlReader object.
Dim reader as XmlReader = XmlReader.Create("https://ServerName/data/books.xml", settings)
// Create a resolver with default credentials.
XmlUrlResolver resolver = new XmlUrlResolver();
resolver.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Set the reader settings object to use the resolver.
settings.XmlResolver = resolver;

// Create the XmlReader object.
XmlReader reader = XmlReader.Create("https://ServerName/data/books.xml", settings);
// Create a resolver with default credentials.
XmlUrlResolver^ resolver = gcnew XmlUrlResolver;
resolver->Credentials = System::Net::CredentialCache::DefaultCredentials;

 // Set the reader settings object to use the resolver.
 settings->XmlResolver = resolver;

// Create the XmlReader object.
XmlReader^ reader = XmlReader::Create( L"https://ServerName/data/books.xml", settings );

不同的凭据可以提供给不同的 URI 并添加到凭据缓存中。 这些凭据用于检查不同 URI 的身份验证,与 XML 的原始源无关。 下面的示例显示如何将凭据添加到缓存中。

' Create the credentials.
Dim myCred As NetworkCredential = New NetworkCredential(UserName,SecurelyStoredPassword,Domain)
Dim myCache As CredentialCache = New CredentialCache()
myCache.Add(new Uri("https://www.contoso.com/"), "Basic", myCred)
myCache.Add(new Uri("http://app.contoso.com/"), "Basic", myCred)

' Set the credentials on the XmlUrlResolver object.
Dim resolver As XmlUrlResolver = New XmlUrlResolver()
resolver.Credentials = myCache

' Compile the style sheet.
Dim xslt As XslCompiledTransform = New XslCompiledTransform()
xslt.Load("https://serverName/data/xsl/order.xsl", XsltSettings.Default, resolver)

// Create the credentials.
NetworkCredential myCred = new NetworkCredential(UserName,SecurelyStoredPassword,Domain); 
CredentialCache myCache = new CredentialCache(); 
myCache.Add(new Uri("https://www.contoso.com/"), "Basic", myCred); 
myCache.Add(new Uri("http://app.contoso.com/"), "Basic", myCred);

// Set the credentials on the XmlUrlResolver object.
XmlUrlResolver resolver = new XmlUrlResolver();
resolver.Credentials = myCache;

// Compile the style sheet.
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load("https://serverName/data/xsl/order.xsl",XsltSettings.Default, resolver);   

请参见

参考

NetworkCredential

CredentialCache

概念

使用 XmlResolver 解析资源

其他资源

解析由 URI 命名的外部 XML 资源