title: C# Swagger generated client how to authenticate and use autogenerated code
body: <p>I have sucessfully generated classes from Swagger Definition (Openapi 3.0.3) using nSwag Studio, but I have no idea how to properly use this as a client.</p>
  <p>Manually RestSharp code works fine, but I'd like to use autogenerated code to consume webservice methods and can't do it properly</p>
  <p>This is working fine:</p>
  <pre><code>string clientId = &quot;dev&quot;;
  string clientSecret = @&quot;pass&quot;;
  
  var client = new RestClient(&quot;http://192.168.1.10/xyz/api/oauth/token&quot;);
  var request = new RestRequest(Method.POST);
  request.AddHeader(&quot;cache-control&quot;, &quot;no-cache&quot;);
  request.AddHeader(&quot;content-type&quot;, &quot;application/x-www-form-urlencoded&quot;);
  request.AddHeader(&quot;grant_type&quot;, &quot;client_credentials&quot;);
  
  var credentials = string.Format(&quot;{0}:{1}&quot;, clientId, clientSecret);
  var headerValue = Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials));
  request.AddHeader(&quot;Authorization&quot;, $&quot;Basic {headerValue}&quot;);
  request.AddParameter($&quot;application/x-www-form-urlencoded&quot;, $&quot;grant_type=client_credentials&amp;client_id={clientId}&amp;client_secret{clientSecret}&quot;, ParameterType.RequestBody);
  IRestResponse response = client.Execute(request, Method.POST);
  </code></pre>
  <p>My try with autogenerated code. My apoligizes if its wrong, but can't find any example.
  There's just few examples but looks like client is generated in a different way (client initialization with base url - but still no idea about basic authorization in this context)
  Googling returns mostly &quot;How to create server side&quot; or add swagger to asp/mvc/webapi project.</p>
  <pre><code>        string URL = @&quot;http://192.168.1.10/xyz/api&quot;;
          string clientId = &quot;dev&quot;;
          string clientSecret = @&quot;pass&quot;;
  
          IO.Swagger.Client.ApiClient client = new IO.Swagger.Client.ApiClient(URL);
          IO.Swagger.Client.Configuration.DefaultApiClient = client; //&lt;&lt;this throws error
          IO.Swagger.Client.Configuration.Username = clientId;
          IO.Swagger.Client.Configuration.Password = clientSecret;
          client.AddDefaultHeader(&quot;Authorization&quot;, &quot;bearer TOKEN&quot;);
  
          IO.Swagger.Api.AuthApi authApi = new IO.Swagger.Api.AuthApi(client);
  </code></pre>
  <p>Error in ApiClient class</p>
  <pre><code>public ApiClient(String basePath=&quot;/xyz/api&quot;)
  {
  BasePath = basePath;
  RestClient = new RestClient(BasePath); //System.UriFormatException: 'Invalid URI: The format of the URI could not be determined.'
  }
  </code></pre>
  <p>I have tried many string forms of url (class doesn't accept Uri explictly)</p>
  <p>Configuration</p>
  <pre><code>using System;
  using System.Reflection;
  using System.Collections.Generic;
  using System.IO;
  using System.Linq;
  using System.Text;
  
  namespace IO.Swagger.Client
  {
      public class Configuration
      {
          public const string Version = &quot;1.0.0&quot;;
          public static ApiClient DefaultApiClient = new ApiClient();
          public static String Username { get; set; }
          public static String Password { get; set; }
          public static Dictionary&lt;String, String&gt; ApiKey = new Dictionary&lt;String, String&gt;();
          public static Dictionary&lt;String, String&gt; ApiKeyPrefix = new Dictionary&lt;String, String&gt;();
          private static string _tempFolderPath = Path.GetTempPath();
          public static String TempFolderPath
          {
              get { return _tempFolderPath; }
    
              set 
              {
                  if (String.IsNullOrEmpty(value))
                  {
                      _tempFolderPath = value;
                      return;
                  }
        
                  // create the directory if it does not exist
                  if (!Directory.Exists(value)) 
                      Directory.CreateDirectory(value);
        
                  // check if the path contains directory separator at the end
                  if (value[value.Length - 1] == Path.DirectorySeparatorChar)
                      _tempFolderPath = value;
                  else
                      _tempFolderPath = value  + Path.DirectorySeparatorChar;
              }
          }
  
          private const string ISO8601_DATETIME_FORMAT = &quot;o&quot;;
          private static string _dateTimeFormat = ISO8601_DATETIME_FORMAT;
  
          public static String DateTimeFormat
          {
              get
              {
                  return _dateTimeFormat;
              }
              set
              {
                  if (string.IsNullOrEmpty(value))
                  {
                      // Never allow a blank or null string, go back to the default
                      _dateTimeFormat = ISO8601_DATETIME_FORMAT;
                      return;
                  }
  
                  // Caution, no validation when you choose date time format other than ISO 8601
                  // Take a look at the above links
                  _dateTimeFormat = value;
              }
          }
  
          public static String ToDebugReport()
          {
              String report = &quot;C# SDK (IO.Swagger) Debug Report:\n&quot;;
              report += &quot;    OS: &quot; + Environment.OSVersion + &quot;\n&quot;;
              report += &quot;    .NET Framework Version: &quot; + Assembly
                       .GetExecutingAssembly()
                       .GetReferencedAssemblies()
                       .Where(x =&gt; x.Name == &quot;System.Core&quot;).First().Version.ToString()  + &quot;\n&quot;;
              report += &quot;    Version of the API: 2.0.1\n&quot;;
              report += &quot;    SDK Package Version: 1.0.0\n&quot;;
    
              return report;
          }
      }
  }
  </code></pre>
  <p>Client</p>
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Globalization;
  using System.Text.RegularExpressions;
  using System.IO;
  using System.Web;
  using System.Linq;
  using System.Net;
  using System.Text;
  using Newtonsoft.Json;
  using RestSharp;
  using RestSharp.Extensions;
  
  namespace IO.Swagger.Client
  {
      public class ApiClient
      {
          private readonly Dictionary&lt;String, String&gt; _defaultHeaderMap = new Dictionary&lt;String, String&gt;();
    
          public ApiClient(String basePath=&quot;/xyz/api&quot;)
          {
              BasePath = basePath;
              RestClient = new RestClient(BasePath);
          }
      
          public string BasePath { get; set; }
          public RestClient RestClient { get; set; }
          public Dictionary&lt;String, String&gt; DefaultHeader
          {
              get { return _defaultHeaderMap; }
          }
          public Object CallApi(String path, RestSharp.Method method, Dictionary&lt;String, String&gt; queryParams, String postBody,
              Dictionary&lt;String, String&gt; headerParams, Dictionary&lt;String, String&gt; formParams, 
              Dictionary&lt;String, FileParameter&gt; fileParams, String[] authSettings)
          {
  
              var request = new RestRequest(path, method);
     
              UpdateParamsForAuth(queryParams, headerParams, authSettings);
  
              // add default header, if any
              foreach(var defaultHeader in _defaultHeaderMap)
                  request.AddHeader(defaultHeader.Key, defaultHeader.Value);
  
              // add header parameter, if any
              foreach(var param in headerParams)
                  request.AddHeader(param.Key, param.Value);
  
              // add query parameter, if any
              foreach(var param in queryParams)
                  request.AddParameter(param.Key, param.Value, ParameterType.GetOrPost);
  
              // add form parameter, if any
              foreach(var param in formParams)
                  request.AddParameter(param.Key, param.Value, ParameterType.GetOrPost);
  
              // add file parameter, if any
              foreach(var param in fileParams)
                  request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentType);
  
              if (postBody != null) // http body (model) parameter
                  request.AddParameter(&quot;application/json&quot;, postBody, ParameterType.RequestBody);
  
              return (Object)RestClient.Execute(request);
  
          }
      
          public void AddDefaultHeader(string key, string value)
          {
              _defaultHeaderMap.Add(key, value);
          }
      
          public string EscapeString(string str)
          {
              return RestSharp.Contrib.HttpUtility.UrlEncode(str);
          }
      
          public FileParameter ParameterToFile(string name, Stream stream)
          {
              if (stream is FileStream)
                  return FileParameter.Create(name, stream.ReadAsBytes(), Path.GetFileName(((FileStream)stream).Name));
              else
                  return FileParameter.Create(name, stream.ReadAsBytes(), &quot;no_file_name_provided&quot;);
          }
      
          public string ParameterToString(object obj)
          {
              if (obj is DateTime)
                  // Return a formatted date string - Can be customized with Configuration.DateTimeFormat
                  // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern (&quot;o&quot;)
                  // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8
                  // For example: 2009-06-15T13:45:30.0000000
                  return ((DateTime)obj).ToString (Configuration.DateTimeFormat);
              else if (obj is List&lt;string&gt;)
                  return String.Join(&quot;,&quot;, (obj as List&lt;string&gt;).ToArray());
              else
                  return Convert.ToString (obj);
          }
      
          public object Deserialize(string content, Type type, IList&lt;Parameter&gt; headers=null)
          {
              if (type == typeof(Object)) // return an object
              {
                  return content;
              }
  
              if (type == typeof(Stream))
              {
                  var filePath = String.IsNullOrEmpty(Configuration.TempFolderPath)
                      ? Path.GetTempPath()
                      : Configuration.TempFolderPath;
  
                  var fileName = filePath + Guid.NewGuid();
                  if (headers != null)
                  {
                      var regex = new Regex(@&quot;Content-Disposition:.*filename=['&quot;&quot;]?([^'&quot;&quot;\s]+)['&quot;&quot;]?$&quot;);
                      var match = regex.Match(headers.ToString());
                      if (match.Success)
                          fileName = filePath + match.Value.Replace(&quot;\&quot;&quot;, &quot;&quot;).Replace(&quot;'&quot;, &quot;&quot;);
                  }
                  File.WriteAllText(fileName, content);
                  return new FileStream(fileName, FileMode.Open);
  
              }
  
              if (type.Name.StartsWith(&quot;System.Nullable`1[[System.DateTime&quot;)) // return a datetime object
              {
                  return DateTime.Parse(content,  null, System.Globalization.DateTimeStyles.RoundtripKind);
              }
  
              if (type == typeof(String) || type.Name.StartsWith(&quot;System.Nullable&quot;)) // return primitive type
              {
                  return ConvertType(content, type); 
              }
      
              // at this point, it must be a model (json)
              try
              {
                  return JsonConvert.DeserializeObject(content, type);
              }
              catch (IOException e)
              {
                  throw new ApiException(500, e.Message);
              }
          }
      
          public string Serialize(object obj)
          {
              try
              {
                  return obj != null ? JsonConvert.SerializeObject(obj) : null;
              }
              catch (Exception e)
              {
                  throw new ApiException(500, e.Message);
              }
          }
      
          public string GetApiKeyWithPrefix (string apiKeyIdentifier)
          {
              var apiKeyValue = &quot;&quot;;
              Configuration.ApiKey.TryGetValue (apiKeyIdentifier, out apiKeyValue);
              var apiKeyPrefix = &quot;&quot;;
              if (Configuration.ApiKeyPrefix.TryGetValue (apiKeyIdentifier, out apiKeyPrefix))
                  return apiKeyPrefix + &quot; &quot; + apiKeyValue;
              else
                  return apiKeyValue;
          }
      
          public void UpdateParamsForAuth(Dictionary&lt;String, String&gt; queryParams, Dictionary&lt;String, String&gt; headerParams, string[] authSettings)
          {
              if (authSettings == null || authSettings.Length == 0)
                  return;
  
              foreach (string auth in authSettings)
              {
                  // determine which one to use
                  switch(auth)
                  {
                      case &quot;BasicAuth&quot;:
                          headerParams[&quot;Authorization&quot;] = &quot;Basic &quot; + Base64Encode(Configuration.Username + &quot;:&quot; + Configuration.Password);
                          
                          break;
                      case &quot;BearerAuth&quot;:
                          
                          
                          break;
                      default:
                          //TODO show warning about security definition not found
                          break;
                  }
              }
          }
   
          public static string Base64Encode(string text)
          {
              var textByte = System.Text.Encoding.UTF8.GetBytes(text);
              return System.Convert.ToBase64String(textByte);
          }
      
          public static Object ConvertType(Object fromObject, Type toObject) {
              return Convert.ChangeType(fromObject, toObject);
          }
      }
  }
  </code></pre>
  <p>AuthApi</p>
  <pre><code>using System;
  using System.Collections.Generic;
  using RestSharp;
  using IO.Swagger.Client;
  using IO.Swagger.Model;
  
  namespace IO.Swagger.Api
  {
      public interface IAuthApi
      {
          InlineResponse200 OauthTokenPost (string grantType);
      }
    
      public class AuthApi : IAuthApi
      {
          public AuthApi(ApiClient apiClient = null)
          {
              if (apiClient == null) // use the default one in Configuration
                  this.ApiClient = Configuration.DefaultApiClient; 
              else
                  this.ApiClient = apiClient;
          }
      
          public AuthApi(String basePath)
          {
              this.ApiClient = new ApiClient(basePath);
          }
      
          public void SetBasePath(String basePath)
          {
              this.ApiClient.BasePath = basePath;
          }
      
          public String GetBasePath(String basePath)
          {
              return this.ApiClient.BasePath;
          }
      
          public ApiClient ApiClient {get; set;}
      
          public InlineResponse200 OauthTokenPost (string grantType)
          {
      
              var path = &quot;/oauth/token&quot;;
              path = path.Replace(&quot;{format}&quot;, &quot;json&quot;);
                  
              var queryParams = new Dictionary&lt;String, String&gt;();
              var headerParams = new Dictionary&lt;String, String&gt;();
              var formParams = new Dictionary&lt;String, String&gt;();
              var fileParams = new Dictionary&lt;String, FileParameter&gt;();
              String postBody = null;
      
              if (grantType != null) formParams.Add(&quot;grant_type&quot;, ApiClient.ParameterToString(grantType)); // form parameter
                  
              // authentication setting, if any
              String[] authSettings = new String[] { &quot;BasicAuth&quot; };
      
              // make the HTTP request
              IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
      
              if (((int)response.StatusCode) &gt;= 400)
                  throw new ApiException ((int)response.StatusCode, &quot;Error calling OauthTokenPost: &quot; + response.Content, response.Content);
              else if (((int)response.StatusCode) == 0)
                  throw new ApiException ((int)response.StatusCode, &quot;Error calling OauthTokenPost: &quot; + response.ErrorMessage, response.ErrorMessage);
      
              return (InlineResponse200) ApiClient.Deserialize(response.Content, typeof(InlineResponse200), response.Headers);
          }
      
      }
  }
  </code></pre>