部署的Web应用邮件发送失败,WebClient请求返回401未授权错误求助
Let's start with the most obvious issue in your code: you're overwriting the WebClient credentials three times in sequence, which creates conflicts and renders your explicit username/password setup useless. Here's the breakdown:
- When you set
client.UseDefaultCredentials = true;, this overwrites theCredentialsvalue you just set withnew NetworkCredential(...)— it forces the WebClient to use the credentials of the user running your application (like the IIS app pool identity, not your local account). - Then setting
client.Credentials = CredentialCache.DefaultCredentials;is redundant, as it does the exact same thing asUseDefaultCredentials = true— you're just repeating the same override.
Fix the Credential Configuration First
Choose one approach based on your needs and stick to it:
1. Use a Specific Username/Password (Not the App's Running User)
If you need to use the Network_Username and Network_Password you defined, remove the other two lines entirely:
// Only keep this line — no UseDefaultCredentials or DefaultCredentials client.Credentials = new NetworkCredential(Network_Username, Network_Password); // Optional: If the target server requires a specific auth type (e.g., NTLM, Basic), use CredentialCache var credentialCache = new CredentialCache(); credentialCache.Add( new Uri("https://your-target-resource-url.com"), // Replace with your actual endpoint "NTLM", // Or "Basic", "Negotiate" — match the server's auth requirements new NetworkCredential(Network_Username, Network_Password) ); client.Credentials = credentialCache;
2. Use the Application's Default Credentials
If you want to use the identity of the user running your web app (e.g., the IIS app pool account), use only one of these equivalent lines:
client.UseDefaultCredentials = true; // OR // client.Credentials = CredentialCache.DefaultCredentials;
Additional Troubleshooting Steps
Once you fix the credential conflict, check these common causes for the 401 error:
- Verify username format: Some servers require the full domain prefix, like
DOMAIN\Usernameinstead of justUsername. - Check the app's running identity: If using
UseDefaultCredentials, confirm the IIS app pool (or service account running your app) has permission to access the target resource. - Confirm the server's auth method: Is the target server using Basic Auth (which may require SSL), NTLM, or Kerberos? Match your credential setup to the server's requirements.
- Link to email failure: Is the 401 error tied to downloading a resource for your email (like a template or attachment)? Double-check the URL your WebClient is hitting, and ensure the account has access to it.
- Test credentials externally: Use a tool like Postman or
curlto hit the same URL with your username/password — if that fails, the issue is with credentials/permissions, not your code.
内容的提问来源于stack exchange,提问作者Karlord
相关产品推荐
相关产品推荐

