我有一个使用C#和MVC构建的Dot Net应用程序。我必须使用SOAPUI API,但是在尝试执行此操作时遇到错误403,即使我可以访问P12证书及其密码。我已经粘贴了下面的代码,跳过了任何不重要的部分。
public string anotherPostDataAttempt()
{
try
{
X509Certificate2 cert = new X509Certificate2
(@"C:\Users\...\Visual Studio 2015\Projects\...\certificateFile.P12", "thisIsThePassword");
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(True);
string url = "https://...";
//HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
string xmlString = "";
StreamReader f_read = new StreamReader(@"C:\Users\...\Desktop\testFile.xml");
xmlString = f_read.ReadToEnd();
f_read.Close();
string DataToPost = xmlString;
String result = "";
String strPost = "RequestXML=" + DataToPost;
StreamWriter myWriter = null;
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Method = "POST";
objRequest.ContentLength = strPost.Length;
//objRequest.ContentType = "text/xml; charset=utf-8";
objRequest.ContentType = "application/x-www-form-urlencoded";
//objRequest.Credentials = CredentialCache.DefaultNetworkCredentials;
objRequest.ClientCertificates.Add(cert);
try
{
myWriter = new StreamWriter(objRequest.GetRequestStream());
myWriter.Write(strPost);
}
catch (Exception e)
{
//
}
finally
{
myWriter.Close();
}
//The program crashes on the line below
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
// Close and clean up the StreamReader
sr.Close();
}
return result;
}
catch (Exception ex)
{
throw ex;
}
}
为了记录,我已经咨询了this blog post in the subject matter,但我猜测我一定做错了,或者我不会得到这个错误。
完整错误:
System.Net.WebException: The remote server returned an error: (403) Forbidden.
InnerException: Null.
Message: The remote server returned an error: (403) Forbidden.