NetworkCredential error in ASP.NET

2019-06-20 08:24发布

I am trying to access a webpage through ASP.NET using the NetworkCredential class. However I keep getting an exception with the following message System.Security.Cryptography.CryptographicException: The handle is invalid

Below is my code on how I am trying to call the function. Any help is greatly appreciated.

C#:

System.Net.WebClient client = new System.Net.WebClient();
client.Credentials = new System.Net.NetworkCredential("Admin", "Nimda");

Stack Trace

[CryptographicException: The handle is invalid.
]

System.Security.SecureString.ProtectMemory() +154
   System.Security.SecureString.InitializeSecureString(Char* value, Int32 length) +170
   System.Security.SecureString..ctor(Char* value, Int32 length) +65
   System.Net.SecureStringHelper.CreateSecureString(String plainString) +6181188
   System.Net.NetworkCredential..ctor(String userName, String password) +64

3条回答
等我变得足够好
2楼-- · 2019-06-20 09:14

This should work in a standard powershell console:

Add-Type -AssemblyName System.Net
$client = New-Object System.Net.WebClient
$netc = New-Object System.Net.NetworkCredential("Admin", "Nimda")
$client.Credentials = $netc

Will be interesting to see if this generates the same invalid handle error.

Edit: Apologies, there was a typo in the 2nd line.

查看更多
姐就是有狂的资本
3楼-- · 2019-06-20 09:22

I've just hit this same problem. I was happening locally under the ASP.NET Development Server in VS 2010. When I executed the app under my Windows 7 / IIS 7, it worked just fine. Hope this helps!

查看更多
该账号已被封号
4楼-- · 2019-06-20 09:24

Ok this is a bit awkward - I've had a look and the error is down to your windows configuration .... somewhere.

The part of the code that's throwing an Exception is actually an interop call to a function in advapi32.dll, specifically:

int status = Win32Native.SystemFunction040(this.m_buffer, (uint) (this.m_buffer.Length * 2), 0);
if (status < 0)
{
    throw new CryptographicException(Win32Native.LsaNtStatusToWinError(status));
}
this.m_encrypted = true;

Calls:

[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success), DllImport("advapi32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
internal static extern int SystemFunction040([In, Out] SafeBSTRHandle pDataIn, [In] uint cbDataIn, [In] uint dwFlags);

That's returning an error code, causing your exception.

If you're in a workplace, you might want to talk with your sysadmin/network guys to see if there's anything in your local policies that might cause a failure. Otherwise, I'd see what happens if you disable your Anti-virus/disable firewall/turn of any 3rd party proxy software.

Basically, anything that overrides default network functionality. Also, might be worth checking you have all the latest windows updates and that you dont have any virus or malware infection.

Sorry I can't be more specific, but I don't believe this is a .Net/programming error.

查看更多
登录 后发表回答