2011-04-05 60 views
2

我正在測試一個我希望用來發布的aspx頁面,但我似乎無法用數據發送證書。這裏是我的客戶端代碼:如何在HttpWebRequest中包含X509Certificate?

System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); 
string postData = "age=23&state=47"; 
byte[] data = encoding.GetBytes(postData); 
X509Certificate x509certificate = X509Certificate.CreateFromCertFile(@"C:\Documents and Settings\rcimbalo\My Documents\Downloads\SSL Certificates\testCert.cer"); 
string key = x509certificate.GetPublicKeyString(); 
string certData = Encoding.ASCII.GetString(x509certificate.Export(X509ContentType.Cert)); 
string pks12 = Encoding.ASCII.GetString(x509certificate.Export(X509ContentType.Pkcs12)); 
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://localhost:3493/Index.aspx"); 
myRequest.Credentials = new NetworkCredential("xxxx", "yyyy"); 
myRequest.Method = "POST"; 
myRequest.ContentType = "application/x-www-form-urlencoded"; 
myRequest.ContentLength = data.Length; 
myRequest.ClientCertificates.Add(x509certificate); 
Stream newStream = myRequest.GetRequestStream(); 
newStream.Write(data, 0, data.Length); 
newStream.Close(); 
System.IO.StreamReader st = new StreamReader(((HttpWebResponse)myRequest.GetResponse()).GetResponseStream()); 
Console.Write(st.ReadLine()); 

,這裏是從我的aspx頁面代碼:

protected void Page_Load(object sender, EventArgs e) 
{ 
if (this.CheckCredentials()) 
{ 
    string data = this.Context.Request.Form.ToString(); 
} 
} 

private bool CheckCredentials() 
{ 
    string userName = User.Identity.Name; 
    HttpClientCertificate certificate = Request.ClientCertificate; 
    if (certificate.IsPresent) 
    { 
     string w = certificate.Get("SUBJECT 0"); 
     return true; 
    } 
    return false; 
} 

從未有一個存在的證書。

我發現這個以前的職位 X509Certificate not getting transmitted to the server

但不明白的答案。我使用MakeCert.exe實用程序創建了一個證書,但我不明白爲什麼它不起作用。

回答

2

客戶端證書通過SSL connection(https:// ....)發送。這對於內置的asp.net開發服務器來說是不可能的,但如果使用新的IIS Express或本地IIS實例則可能。