Search code examples
c#biztalkrestsharpbiztalk-2016

Using C# Restharp Method in BizTalk, throws NullReferenceException "Object reference not set to an instance of an object"


    public static string getAccessToken()
    {
       
            var client = new RestClient("...");
            client.Timeout = -1;
            var request = new RestRequest() { Method = Method.POST };
            request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
            request.AddParameter("grant_type", "client_credentials");
            request.AddParameter("client_id", "...");
            request.AddParameter("client_secret", "...");
            IRestResponse token = client.Execute(request);
            string varToken = token.Content;
          
            return varToken;
        
    }

This method to get the token works ! But the method to use the token throws an NullReferenceException "Object reference not set to an instance of an object"

    public static string testAccessToken(string token)
    {
       
       var client = new RestClient("...");
       client.Timeout = -1;
       var request = new RestRequest(Method.GET);
       request.AddHeader("Content-Type", "application/json");
       request.AddHeader("Authorization", "Bearer " + token);

       IRestResponse response = client.Execute(request);
       string varToken = response.Content;

       
       return varToken;
       
        
    }

When I test the method testAccessToken(string token) in a Visual Studio Form Application it works, but when I use it it BizTalk it throws an NullReferenceException "Object reference not set to an instance of an object"

Anyone have an idea how to solve this ?


Solution

  • Problem solved. Even though in a sample Windows Form application the created Restsharp class returned a result, the same class in Biztalk returned nothing. The cause is the TLS encryption. Many servers still allow TLS 1.0 to 1.2, but servers in the OAuth2 environment explicitly allow 1.2, including the Mircosoft servers for Business Central.

    Two ways lead to the goal. First, set TLS 1.2 as the default protocol in Windows. Manual registry changes are necessary for this. However, these changes on customer servers can lead to the fact that other applications of the customer cannot communicate any more.

    The better way is to tell Restsharp on every call which encryption should be used. "System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12"

    and voila, Biztalk finally got a result back from the class.