twilio-csharp

repository·main·Indexed 20 days ago

https://github.com/twilio/twilio-csharp

The official Twilio REST API and TwiML library for .NET, supporting .NET 6+. It enables developers to programmatically manage Twilio resources, send and receive SMS, and initiate phone calls using C#. The library includes strongly-typed classes for generating TwiML XML responses and provides advanced configuration options for custom HTTP clients, proxy server integration, and debug logging.

Tokens
4.6K
Snippets
20
Records
25
Agent score
72%

What's inside twilio-csharp

  1. Use custom HTTP clients for advanced networking or testing

    main

    Injecting a custom TwilioRestClient is not limited to proxy usage. You can also use this technique to:

    • Add custom HTTP headers: Useful if an upstream proxy or security layer requires specific headers for all outgoing requests.
    • Mocking for Unit Tests: Implement the Twilio.Http.HttpClient interface to return mocked responses, allowing you to test your application logic without making actual network calls to Twilio.
  2. Understand Twilio API Annotations

    main

    The library uses specific attributes to indicate the stability of features:

    • [Beta]: Features in beta stage; may undergo changes and are not guaranteed to be stable.
    • [Preview]: Features in preview stage; intended for evaluation and subject to change. Not recommended for production without thorough testing.
    • [Deprecated]: Features that are no longer encouraged for use.
  3. How Twilio.Http.HttpClient and SystemNetHttpClient work together

    main

    The TwilioRestClient constructor accepts an httpClient parameter of type Twilio.Http.HttpClient. This is an abstraction layer that allows for custom implementations or mocking.

    To use the standard .NET System.Net.Http.HttpClient, you must wrap it in a Twilio.Http.SystemNetHttpClient before passing it to the TwilioRestClient constructor.

  4. Understand the twilio-csharp versioning strategy

    main

    The library follows a modified Semantic Versioning (MAJOR.MINOR.PATCH) model. To prevent unexpected breaking changes, it is strongly recommended to pin at least the major version in your project dependencies.

    • PATCH (MAJOR.MINOR.PATCH): Incremented for backwards-compatible bug fixes. These are generally safe to upgrade.
    • MINOR (MAJOR.MINOR.PATCH): Incremented when new features are added or small, backwards-incompatible changes (like function signature changes) are introduced. Upgrading may require manual code adjustments.
    • MAJOR (MAJOR.MINOR.PATCH): Incremented for large-scale breaking changes that require extensive code reworking. These are rare and communicated in advance via Release Candidates.
  5. Identify supported versions of twilio-csharp

    main
    Only the current MAJOR version of twilio-csharp is officially supported. New features, functionality, bug fixes, and security updates are exclusively provided for the current major version. If you are using an older major version, you will not receive updates.
  6. Connect to a proxy server using a custom TwilioRestClient

    main

    To route Twilio API requests through an enterprise proxy server, you can create a custom TwilioRestClient that uses a System.Net.Http.HttpClient configured with a WebProxy and appropriate authentication headers.

    Steps to implement:

    1. Create a System.Net.Http.HttpClientHandler and set its Proxy property using a WebProxy object.
    2. Initialize a System.Net.Http.HttpClient with that handler.
    3. If the proxy requires authentication, add a Basic authorization header to the HttpClient.DefaultRequestHeaders.
    4. Wrap the HttpClient in a Twilio.Http.SystemNetHttpClient.
    5. Pass that wrapper to the TwilioRestClient constructor.
    // Example of wrapping a proxied HttpClient for Twilio
    var handler = new HttpClientHandler()
    {
        Proxy = new WebProxy(proxyUrl),
        UseProxy = true
    };
    var httpClient = new HttpClient(handler);
    
    // Add proxy credentials if needed
    var byteArray = Encoding.Unicode.GetBytes(username + ":" + password);
    httpClient.DefaultRequestHeaders.Authorization = 
        new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
    
    var twilioRestClient = new TwilioRestClient(
        accountSid, 
        authToken, 
        httpClient: new Twilio.Http.SystemNetHttpClient(httpClient)
    );
  7. Install the Twilio NuGet package

    main

    You can add the Twilio libraries to your .NET project using the NuGet package manager. This library supports .NET applications utilizing .NET 6+.

    ### With Visual Studio IDE
    
    ```shell
    Install-Package Twilio

    With .NET Core Command Line Tools

    dotnet add package Twilio
  8. Inject a custom TwilioRestClient into API resource actions

    main

    By default, the Twilio helper library creates a default TwilioRestClient using credentials provided via TwilioClient.Init. However, you can instantiate your own TwilioRestClient and pass it as the client parameter to any Twilio REST API resource action (e.g., MessageResource.Create). This allows you to control the underlying HTTP transport layer.

    var twilioRestClient = ProxiedTwilioClientCreator.GetClient();
    
    var message = MessageResource.Create(
        to: new PhoneNumber("+15017122661"),
        from: new PhoneNumber("+15017122661"),
        body: "Hey there!",
        client: twilioRestClient // Inject the custom client here
    );
  9. Resolve Json.NET / Newtonsoft.Json version conflicts

    main

    If your project requires a different version of Newtonsoft.Json than the one specified by the Twilio helper library, you may encounter versioning conflicts. You can resolve this by enabling binding redirection (either automatically or manually) or by using a quick fix in Visual Studio.

    To apply the quick fix for existing projects in Visual Studio:

    1. Open the Package Manager Console via Tools > NuGet Package Manager > Package Manager Console.
    2. Run the following command to add binding redirects to all projects in your solution.
    Get-Project –All | Add-BindingRedirect
  10. Enable TLS 1.2 for REST API access

    main

    New Twilio accounts and subaccounts require TLS 1.2. If you encounter "Upgrade Required" errors (error code 20426), ensure your .NET application is configured to use TLS 1.2.

    System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
  11. Initiate an outbound call and send an SMS

    main

    Use TwilioClient.Init to authenticate with your ACCOUNT_SID and AUTH_TOKEN. You can then use CallResource.Create to initiate phone calls and MessageResource.Create to send SMS messages.

    TwilioClient.Init("ACCOUNT_SID", "AUTH_TOKEN");
    
    var call = CallResource.Create(
        new PhoneNumber("+11234567890"),
        from: new PhoneNumber("+10987654321"),
        url: new Uri("https://my.twiml.here")
    );
    Console.WriteLine(call.Sid);
    
    var message = MessageResource.Create(
        new PhoneNumber("+11234567890"),
        from: new PhoneNumber("+10987654321"),
        body: "Hello World!"
    );
    Console.WriteLine(message.Sid);
  12. Generate TwiML XML responses

    main

    TwiML (Twilio Markup Language) can be generated using strongly-typed C# classes. You can create elements standalone, set attributes directly, or use helper methods on a VoiceResponse object to append elements. The resulting object can be serialized to an XML string.

    // TwiML classes can be created as standalone elements
    var gather = new Gather(numDigits: 1, action: new Uri("hello-monkey-handle-key.cshtml"), method: HttpMethod.Post)
        .Say("To speak to a real monkey, press 1. Press 2 to record your own monkey howl. Press any other key to start over.");
    
    // Attributes can be set directly on the object
    gather.Timeout = 100;
    gather.MaxSpeechTime = 200
    
    // Arbitrary attributes can be set by calling set/getOption
    var dial = new Dial().SetOption("myAttribute", 200)
                         .SetOption("newAttribute", false);
    
    // Or can be created and attached to a response directly using helper methods
    var response = new VoiceResponse()
        .Say("Hello Monkey")
        .Play(new Uri("http://demo.twilio.com/hellomonkey/monkey.mp3"))
        .Append(gather)
        .Append(dial);
    
    // Serialize the TwiML objects to XML string
    Console.WriteLine(response);