2008-11-19 75 views
1

我创建了一个SamlAssertion实例,并向其添加了授权声明和属性声明,现在我想打印出XML,以便可以执行HTTP发布,但不能所有的断言都被输出。我错过了什么(我确定它是骨头的)?C#中的SAML Assertion WriteXML问题#

这里是我使用的代码:

// Add the Statements to the SAML Assertion 
    samlAssert.Statements.Add(samlAuthStatement); 
    samlAssert.Statements.Add(samlAttrStatement); 
    MemoryStream xmlStream = new MemoryStream(); 
    XmlDictionaryWriter xmlWriter = XmlDictionaryWriter.CreateTextWriter(xmlStream, System.Text.Encoding.UTF8); 
    SamlSerializer samlAssertSerializer = new SamlSerializer(); 
    WSSecurityTokenSerializer secTokenSerializer = new WSSecurityTokenSerializer(); 
    samlAssert.WriteXml(xmlWriter, samlAssertSerializer, secTokenSerializer); 

    xmlStream.Position = 0; 
    StreamReader sr = new StreamReader(xmlStream, System.Text.Encoding.UTF8); 
    string AssertStr = sr.ReadToEnd(); 
    TextBox1.Text = AssertStr; 

但都被返回是这样的:

<saml:Assertion MajorVersion="1" MinorVersion="1" AssertionID="assertID" 
       Issuer="my Company" IssueInstant="2008-11-19T19:54:12.191Z" 
       xmlns:saml="urn:oasis:names:tc:SAML:1.0:assertion"> 
    <saml:Conditions NotBefore="2008-11-19T19:54:12.191Z" NotOnOrAfter="2008-11-19T19:59:12.191Z"/> 
    <saml:AuthenticationStatement AuthenticationMethod="urn:oasis:names:tc:SAML:2.0:ac:classes:TimeSyncToken" 
            AuthenticationInstant="2008-11-19T19:54:12.191Z"> 
     <saml:Subject> 
      <saml:NameIdentifier Format="cs-sstc-schema-assertion-1.1.xsd" NameQualifier="My company">xxxx</saml:NameIdentifier> 
      <saml:SubjectConfirmation> 
       <saml:ConfirmationMethod>urn:oasis:names:tc:SAML:1.0:cm:bearer</saml:ConfirmationMethod> 
      </saml:SubjectConfirmation> 
     </saml:Subject> 
     <saml:SubjectLocality IPAddress="x.x.x.x"/> 
     </saml: 
+0

我想通了。我需要在XmlDictionaryWriter上调用flush()。虽然如果有人知道更好的方法来实现这一点,我总是上学一点 – mjmcinto 2008-11-19 20:32:11

+0

检查达林的例子与`使用`。 – orip 2010-02-07 09:16:55

回答

4

如果在这种情况下我有一个建议,那么这将是:在使用IDisposable对象(如流)时总是使用using语句。除了自动冲洗流,它也可以在发生异常时释放资源:

// Add the Statements to the SAML Assertion 
samlAssert.Statements.Add(samlAuthStatement); 
samlAssert.Statements.Add(samlAttrStatement); 

var sb = new StringBuilder(); 
var settings = new XmlWriterSettings 
{ 
    OmitXmlDeclaration = true, 
    Encoding = Encoding.UTF8 
}; 
using (var stringWriter = new StringWriter(sb)) 
using (var xmlWriter = XmlWriter.Create(stringWriter, settings)) 
using (var dictionaryWriter = XmlDictionaryWriter.CreateDictionaryWriter(xmlWriter)) 
{ 
    var samlAssertSerializer = new SamlSerializer(); 
    var secTokenSerializer = new WSSecurityTokenSerializer(); 
    samlAssert.WriteXml(
     dictionaryWriter, 
     samlAssertSerializer, 
     secTokenSerializer 
    ); 
} 

TextBox1.Text = sb.ToString();