4
我試圖引用添加到我的安全頁眉和正在運行到一個非常通用的錯誤:畸形的參考元素
Malformed Reference Element
我曾嘗試與類似的結果如下:
- 引用元素在文檔中通過傳入
ID
的元素作爲Reference
對象的URI
。 - 通過
LoadXml()
方法將XmlElement
對象傳遞給Reference
。我通過使用this StackOverflow post上發現的超載GetIdElement
檢索XmlElement
參考。
當我在一個空字符串傳遞作爲URI
,如預期的那樣SignedXml
作品ComputeSignature()
方法。但是,我需要添加最多3個對安全標題的引用。
更新#1
感謝this blog post,我能夠創造從簡化版本,我認爲是什麼原因造成我的問題是使用Namespace
屬性和前綴。
更新#2
看來好像在<Timestamp>
元件的Id
屬性的命名空間聲明,導致發生該錯誤。
UPDATE#3
我想我得到了這個工作。請參閱下面的答案。
工作示例:
請注意Id XAttribute
與定義不起作用的命名空間;而沒有定義名稱空間的Id XAttribute
可以工作。
private void CreateSecurityAndTimestampXML(string fileName)
{
TimestampID = "TS-E" + GUID.NewGuid();
DateTime SecurityTimestampUTC = DateTime.UtcNow;
XDocument xdoc = new XDocument(
new XElement(wsse + "Security",
new XAttribute(XNamespace.Xmlns + "wsse", wsse.NamespaceName),
new XAttribute(XNamespace.Xmlns + "wsu", wsu.NamespaceName),
new XElement(wsu + "Timestamp",
// new XAttribute(wsu + "Id", TimestampID), // <-- Does Not Work
new XAttribute("Id", TimestampID), // <-- Works
new XElement(wsu + "Created", SecurityTimestampUTC.ToString(_timestampFormat)),
new XElement(wsu + "Expires", SecurityTimestampUTC.AddMinutes(10).ToString(_timestampFormat))
)
)
);
using (XmlTextWriter tw = new XmlTextWriter(fileName, new UTF8Encoding(false)))
{
xdoc.WriteTo(tw);
}
}
// Snippet
string[] elements = { TimestampID };
foreach (string s in elements)
{
Reference reference = new Reference()
{
Uri = "#" + s
};
XmlDsigExcC14NTransform env = new XmlDsigExcC14NTransform();
env.InclusiveNamespacesPrefixList = _includedPrefixList;
reference.AddTransform(env);
xSigned.AddReference(reference);
}
// Add Key Info Here.
// Compute the Signature.
xSigned.ComputeSignature();