Win32Exception:The target principal name is incorrect when calling a WCF service with WebClient

后端 未结 2 1133
萌比男神i
萌比男神i 2021-01-24 08:14

I put together a quick chunk of example code with linqpad showing a WCF webservice call without creating a proxy class from the WSDL. Here\'s what I have:

using         


        
2条回答
  •  迷失自我
    2021-01-24 09:09

    From MSDN Site:

    An SPN is a name by which a client uniquely identifies an instance of a service or application on a server for purposes of mutual authentication. Mutual authentication is requested by default, and you can require it by setting WebRequest.AuthenticationLevel to MutualAuthRequired in your request.

    When a WebRequest requires mutual authentication, the SPN for the destination must be supplied by the client. If you know the SPN, you can add it to the CustomTargetNameDictionary before sending the request. If you have not added SPN information to this dictionary, the AuthenticationManager uses the RequestUri method to compose the most likely SPN; however, this is a computed value and might be incorrect. If mutual authentication is attempted and fails, you can check the dictionary to determine the computed SPN. No SPN is entered into the dictionary if the authentication protocol does not support mutual authentication.

    So adding to Authentication.CutomTargetNameDictionary URL and spn, should solve your issue.

    using (var wb = new WebClient())
    {
      const string URL = "http://myserver:55002/Core.svc";
    
      wb.Credentials = CredentialCache.DefaultNetworkCredentials;
      wb.Headers.Add("Content-Type: text/xml;charset=UTF-8");
      wb.Headers.Add("SOAPAction: \"http://tempuri.org/Core/Project_GetNumberForExternalUse\"");
    
      String requestString = @"
        
        
        
            
              
              ext 1
              
              ext 2
              
              ext 3
              
              ext 4
              
              ext 1ext 1ext 1ext 1ext 1
            
        
      
      ";
    
      var uri = new Uri(URL);
      var spn = $"{uri.Scheme}/{uri.Authority}";
      AuthenticationManager.CustomTargetNameDictionary.Add(URL, spn);
    
      var response = wb.UploadString(URL, "POST", requestString);
      response.Dump();
    }
    

提交回复
热议问题