访问Dynamics365触发System.ServiceModel.Security.MessageSecurityException异常求助
Problem Description
I'm hitting this error when trying to pull data from MS Dynamics:
'System.ServiceModel.Security.MessageSecurityException' occurred in Microsoft.Xrm.Sdk.dll but was not handled in user code
Additional information: An unsecured or incorrectly secured fault was received from the other party. See the inner FaultException for the fault code and detail.
The error triggers on this specific line:
EntityCollection collection = service.RetrieveMultiple(query);
Here's my full code implementation:
protected void Page_Load(object sender, EventArgs e) { IOrganizationService service = GetCRMService(); QueryExpression query = new QueryExpression("account"); query.ColumnSet.AllColumns = true; query.Criteria.AddCondition("name", ConditionOperator.NotEqual, "ksllls"); EntityCollection collection = service.RetrieveMultiple(query); DataTable dt = new DataTable(); dt.Columns.Add("name"); dt.Columns.Add("accountnumber"); foreach (Entity entity in collection.Entities) { DataRow dr = dt.NewRow(); dr["name"] = entity.Attributes["name"].ToString(); if (entity.Contains("accountnumber")) { dr["accountnumber"] = entity.Attributes["accountnumber"].ToString(); } dt.Rows.Add(dr); } GridView1.DataSource = dt; GridView1.DataBind(); } public IOrganizationService GetCRMService() { string UserName = "mydomain.com"; string Password = "*****"; ClientCredentials Credentials = new ClientCredentials(); IOrganizationService Service; Credentials.UserName.UserName = UserName; Credentials.UserName.Password = Password; Credentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials; //This URI need to be updated to match the servername and organisation for the environment string CRMServer = ConfigurationManager.AppSettings["crmserverurl"].ToString(); Uri OrganizationUri = new Uri(CRMServer); Uri HomeRealmUri = null; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // OrgaizationServiceProxy ServiceProxy using (OrganizationServiceProxy ServiceProxy = new OrganizationServiceProxy(OrganizationUri, null, Credentials, null)) { Service = (IOrganizationService)ServiceProxy; } return Service; }
Possible Causes & Fixes
Let's walk through the most likely issues and how to resolve them, starting with the most common culprits:
1. Invalid Username Format
Your current UserName is set to "mydomain.com" — this isn't a valid user principal name (UPN). You need to use the full, proper format for your environment:
- For Azure AD/OAuth:
your-actual-username@mydomain.com - For on-premise Windows auth:
mydomain\\your-actual-username
Fix example:
string UserName = "john.doe@mydomain.com";
2. Conflicting Authentication Methods
You're setting both username/password credentials and Windows network credentials in the same code. This creates conflicts because Dynamics only expects one auth method at a time.
- If your environment uses username/password OAuth: Remove the Windows credential line entirely:
// Delete this line: // Credentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials; - If it uses Windows Authentication: Skip setting the
Credentials.UserNameproperties and rely solely on the Windows client credential.
3. Incorrect CRM Server URL
Double-check that your crmserverurl config value is accurate. For online Dynamics environments, it should follow this structure:https://yourorgname.crm.dynamics.com/XRMServices/2011/Organization.svc
Make sure there are no typos, trailing slashes, or wrong protocols (online environments require HTTPS).
4. Missing Service Proxy Configuration
When using OrganizationServiceProxy, adding a couple of key settings can resolve connection issues. Insert these lines inside your using block:
ServiceProxy.EnableProxyTypes(); ServiceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
This ensures the proxy handles entity serialization correctly.
5. Get Precise Details from the Inner Exception
The error message hints at checking the inner FaultException — adding a try-catch block will reveal specific details like invalid permissions, access denial, or URL misconfiguration:
try { EntityCollection collection = service.RetrieveMultiple(query); } catch (MessageSecurityException ex) { if (ex.InnerException is FaultException faultEx) { // Log or display these details for debugging Response.Write($"Fault Code: {faultEx.Code.Name}, Detail: {faultEx.Message}"); } }
6. TLS/SSL Certificate Issues
While you've set Tls12, some environments might have untrusted SSL certificates (common in testing). For temporary testing only, you can bypass certificate validation:
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
⚠️ Never use this in production — instead, ensure your server's SSL certificate is properly trusted by your application server.
Final Recommendation
Start with fixing the username format — that's the most frequent cause of this exact error. If that doesn't resolve it, move on to checking the authentication method and CRM URL. Always use the inner exception details to get targeted insights instead of relying on the generic top-level error message.
内容的提问来源于stack exchange,提问作者Boney Jose

