InvokeIONAPIMethodWithToken2 ION API method

This ION API method calls an ION API endpoint directly using an explicit URL and pre-obtained bearer token, bypassing SSO and Server ID-based authentication. This is enabled for scenarios where a token is already available, such as one returned by GetBearerToken. This method delegates the HTTP call to IONAPIMethodSafe.InvokeIONAPIMethodWithToken2.

Example

Parameter pattern:
  • 0 Token
  • 1 URL
  • 2 APIContext
  • 3 HttpMethod
  • 4 MethodName
  • 5 MethodParams
  • 6 RequestContentType
  • 7 Timeout
  • 8 BinaryResponse
  • 9 HttpResponseCode
  • 10 Response
  • 11 ResponseHeaders
  • 12 Infobar

Return:

response.Parameters[10]
public static int InvokeIONAPIMethodWithToken2( 
                  string token,
                  string URL, 
                  string APIContext, 
                  string httpMethod, 
                  string methodName, 
                  string methodParams, 
                  string requestContentType, 
                  int timeout, 
                  bool binaryResponse,
                  ref int httpResponseCode, 
                  ref string response, 
                  ref string responseHeaders, 
                  ref string infobar )
{
   int returnVar = 0;
   httpResponseCode = -1;
   responseHeaders = string.Empty;
   response = string.Empty;
   try
   {
      // construct HTTP client & add access token
      if ( timeout <= 0 )
         timeout = 60;

      using ( var client = new HttpClient( new HttpClientHandler() { AllowAutoRedirect = false } )
         {
            Timeout = TimeSpan.FromSeconds( timeout ),
            BaseAddress = new Uri( URL )
         } )
      {
         MGLog.LogMessage( IDORuntime.ConfigurationName, "MGCoreExt", LogMessageTypes.Trace, "Invoke ION API method; server base URL: {0}", client.BaseAddress.ToString() );
         RestMethodParameter[] parameters = null;
         List<KeyValuePair<string, string>> queryParams = null;
         string contentString = null;
         client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( "Bearer", token );
         using ( HttpRequestMessage message = new HttpRequestMessage() { Method = new HttpMethod( httpMethod ) } )
         {
            // set method parameters 
            if ( !string.IsNullOrEmpty( methodParams ) )
            {
               try
               {
                  parameters = RestServiceUtil.ParseMethodParameters( methodParams );
                  foreach ( RestMethodParameter p in parameters )
                  {
                     switch ( p.Type )
                     {
                        case ParameterTypes.header:
                           client.DefaultRequestHeaders.Add( p.Name, p.Value.ToString() );
                           break;
                        case ParameterTypes.path:
                           methodName = methodName.Replace( "{" + p.Name + "}", Uri.EscapeDataString( p.Value.ToString() ) );
                           break;
                        case ParameterTypes.query:
                           if ( queryParams == null )
                             queryParams = new List<KeyValuePair<string, string>>();
                           queryParams.Add( new KeyValuePair<string, string>( p.Name, p.Value.ToString() ) );
                           break;
                        case ParameterTypes.body:
                           contentString = p.Value.ToString(); 
                           break;
                     }
                  }
               }
               catch ( Exception e )
               {
                  infobar = string.Format( "Error parsing ION API method parameters: {0}", e.Message );
                  returnVar = 16;
               }
            }

            // continue if no error
            if ( returnVar == 0 )
            {
               using ( StringContent content = ( contentString != null ? new StringContent( contentString ) : null ) )
               using ( FormUrlEncodedContent query = ( queryParams != null && queryParams.Count != 0 ? new FormUrlEncodedContent( queryParams ) : null ) )
               {
                  if ( content != null && !string.IsNullOrEmpty( requestContentType ) )
                  {
                     if ( requestContentType.IndexOf( "multipart/form-data", StringComparison.OrdinalIgnoreCase ) >= 0 )
                     {                          
                        content.Headers.Remove( "Content-Type" );
                        content.Headers.TryAddWithoutValidation( "Content-Type", requestContentType );
                     }
                     else
                     {
                        content.Headers.ContentType = MediaTypeWithQualityHeaderValue.TryParse( requestContentType, out var mediaType ) ? mediaType : new MediaTypeHeaderValue( requestContentType );
                     }
                  }

                  if ( content != null )
                     message.Content = content;
                  
                  // construct URL
                  string requestURL = string.Concat( APIContext, methodName );
                  if ( requestURL.StartsWith( "/" ) )
                     requestURL = requestURL.TrimStart( '/' );
                  if ( query != null )
                     requestURL = string.Format( "{0}?{1}", requestURL, query.ReadAsStringAsync().Result );
                  MGLog.LogMessage( IDORuntime.ConfigurationName, "MGCoreExt", LogMessageTypes.Trace, "Invoke ION API method; relative request URL: {0}", requestURL );
                  message.RequestUri = new Uri( requestURL, UriKind.Relative );
                     
                  var completionOption = binaryResponse ? HttpCompletionOption.ResponseHeadersRead : HttpCompletionOption.ResponseContentRead;

                  // get response
                  using ( HttpResponseMessage httpResponse = client.SendAsync( message, completionOption ).Result )
                  {
                     if ( httpResponse != null )
                     {
                        // set response values
                        httpResponseCode = (int)httpResponse.StatusCode;
                        if ( httpResponse.ReasonPhrase != null )
                           infobar = string.Format( "{0}\r\n{1}", infobar, httpResponse.ReasonPhrase );
                        var headers = new List<KeyValuePair<string, IEnumerable<string>>>();
                        if ( httpResponse.Headers != null )
                        {
                           headers.AddRange( httpResponse.Headers );
                        }

                        // get response content
                        if ( httpResponse.Content != null )
                        {
                           if ( binaryResponse )
                           {
                              try 
                              {
                                 var stream = httpResponse.Content.ReadAsStreamAsync().Result;
                                 response = TextUtil.FormatBinaryStream( stream, httpResponse.Content.Headers.ContentLength.HasValue ? (int)httpResponse.Content.Headers.ContentLength.Value : -1 ); 
                              }
                              catch ( Exception e )
                              {
                                 infobar = string.Format( "Error reading response content: {0}", e.Message );
                                 returnVar = 16;
                              }
                           }
                           else
                           {
                              if ( httpResponse.Content.Headers != null )
                              {
                                 headers.AddRange( httpResponse.Content.Headers );
                              }

                              try { response = httpResponse.Content.ReadAsStringAsync().Result; }
                              catch ( Exception e )
                              {
                                 infobar = string.Format( "Error reading response content: {0}", e.Message );
                                 returnVar = 16;
                              }
                           }
                        }

                        responseHeaders = SerializeHttpHeaders( headers );
                     }
                  }
               }
            }
         }
      }
   }
   catch ( HttpRequestException e )
   {
      returnVar = e.HResult;
      infobar = e.Message;
   }
   catch ( Exception e )
   {
      infobar = e.AllMessagesFlattened();
      throw;
   }

   return returnVar;
}