I have an application written in C# MVC 4, which will run on server, that has one certificate inside the project, in the App_Data folder. I need to get this certificate file to access a Web Service. The server is a Windows Server 2012, using iis7.
The code runs as expected locally, but it does not work on the server. There I receive the message "The system cannot find the file specified". But this file IS there (I return the content of this directory and the previous one, getting them on the browser's console). I tried to rename the certificate from .pfx to .pcertx (a random one) and doesn't work on the server again, although it works locally.
Here's the code I'm using to try to get this file:
public string getCertificado()
{
string path = string.Empty;
try
{
path = HttpContext.Current.Server.MapPath(@"~\App_Data\CERTIFICATE.pcertx");
Byte[] rawCert = File.ReadAllBytes(path);
String certificado = Convert.ToBase64String(rawCert);
_X509Cert.Import(Convert.FromBase64String(certificado), "PASSWORD", X509KeyStorageFlags.PersistKeySet);
client.AddCerts(new X509Certificate[] { _X509Cert });
return string.Empty;
}
catch (Exception ex)
{
// In case of error, list the content of the current directory and the previous
string[] filePaths = Directory.GetFiles(HttpContext.Current.Server.MapPath(@"~\App_Data"));
string pastaAnterior = Path.GetFullPath(Path.Combine(HttpContext.Current.Server.MapPath(@"~\App_Data"), @"..\"));
string[] filePathsAnt = Directory.GetFiles(pastaAnterior);
return "Cannot get certificate." + ex.Message + "; " + ex.InnerException + "; Path: " + path + "; Folder content: " + string.Join("\n",filePaths) + "; Previous folder content" + string.Join("\n",filePathsAnt);
}
}
This is what I get from the browser's console:
"Não foi possível obter nenhum certificado.
The system cannot find the file specified.
Path: C:\Unisys\Management\Applications\sicopplustest\App_Data\CERTIFICATE.pcertx;
Caminho pasta:
C:\Unisys\Management\Applications\sicopplustest\App_Data\CERTIFICATE.pcertx
C:\Unisys\Management\Applications\sicopplustest\App_Data\DynamicAspx.xsl;
Caminho pasta anteriorC:\Unisys\Management\Applications\sicopplustest\ApplicationInfo.Debug.xml C:\Unisys\Management\Applications\sicopplustest\ApplicationInfo.Release.xml C:\Unisys\Management\Applications\sicopplustest\ApplicationInfo.xml ..."
If I got the certificate properly, no message would be sent.
I think it may be related to security, but how can I fix it? I don't know how to procede with this situation.