Menu

Expand
Rate this page:

Chat with C# and ASP.NET MVC

As the Programmable Chat API is set to sunset in 2022, we will no longer maintain these chat tutorials.

Please see our Conversations API QuickStart to start building robust virtual spaces for conversation.

Programmable Chat has been deprecated and is no longer supported. Instead, we'll be focusing on the next generation of chat: Twilio Conversations. Find out more about the EOL process here.

If you're starting a new project, please visit the Conversations Docs to begin. If you've already built on Programmable Chat, please visit our Migration Guide to learn about how to switch.

Ready to implement a chat application using Twilio Chat?

This application allow users to exchange messages through different channels, using the Twilio Chat API. With this example, we'll show you how to use this API to manage channels and their usages.

Properati built a web and mobile messaging app to help real estate buyers and sellers connect in real time. Learn more here.

For your convenience, we consolidated the source code for this tutorial in a single GitHub repository. Feel free to clone it and tweak as required.

Let's get started!

Token Generation

In order to create a Twilio Chat client, you will need an access token. This token provides access for a client (such as a Javascript front end web application) to talk to the Twilio Chat API.

We generate this token by creating a new Token and providing it with an ChatGrant. With the Token at hand, we can use its method ToJwt() to return its string representation.

Loading Code Sample...
        
        
        TwilioChat.Web/Domain/TokenGenerator.cs

        Generate an Access Token

        TwilioChat.Web/Domain/TokenGenerator.cs

        We can generate a token, now we need a way for the chat app to get it.

        Token Generation Controller

        Token Generation Controller

        On our controller we expose an endpoint that provides a valid token. Using the parameter:

        • identity: identifies the user itself.

        It uses tokenGenerator.Generate method to get hold of a new token and return it in a JSON format to be used for our client.

        Loading Code Sample...
              
              
              TwilioChat.Web/Controllers/TokenController.cs

              Token Generation Controller

              TwilioChat.Web/Controllers/TokenController.cs

              Now that we have a route that generates JWT tokens on demand, let's use this route to initialize our Twilio Chat Client.

              Initialize the Chat Client

              Initialize the Chat Client

              On our client, we fetch a new Token using a POST request to our endpoint.

              And with the token we can instantiate a new Twilio.AccessManager that is used to initialize our Twilio.Chat.Client.

              Loading Code Sample...
                    
                    
                    Twilio Chat Client Initialization in JS

                    Initialize the Chat Client

                    Twilio Chat Client Initialization in JS

                    Now that we've initialized our Chat Client, lets see how we can get a list of channels.

                    Get the Channel List

                    Get the Channel List

                    After initializing the client, we can now call it's method getChannels to retrieve all visible channels. The method returns a promise as a result that we use to show the list of channels retrieved on the UI.

                    Loading Code Sample...
                          
                          
                          TwilioChat.Web/Scripts/twiliochat.js

                          Get the Channel List

                          TwilioChat.Web/Scripts/twiliochat.js

                          Next, we need a default channel.

                          Join the General Channel

                          Join the General Channel

                          This application will try to join a channel called "General Channel" when it starts. If the channel doesn't exist, we'll create one with that name. The scope of this example application will show you how to work only with public channels, but the Chat client allows you to create private channels and handle invitations.

                          Notice we set a unique name for the general channel as we don't want to create a new general channel every time we start the application.

                          Loading Code Sample...
                                
                                
                                TwilioChat.Web/Scripts/twiliochat.js

                                Join the General Channel

                                TwilioChat.Web/Scripts/twiliochat.js

                                Now let's listen for some channel events.

                                Listen to Channel Events

                                Listen to Channel Events

                                With access to the channel objects we can use them to listen to a series of events. In our case, we're setting listeners to the following events:

                                • messageAdded: When another member sends a message to the channel you are connected to.
                                • typingStarted: When another member is typing a message on the channel that you are connected to.
                                • typingEnded: When another member stops typing a message on the channel that you are connected to.
                                • memberJoined: When another member joins the channel that you are connected to.
                                • memberLeft: When another member leaves the channel that you are connected to.

                                Here, we just register a different function to handle each particular event.

                                Loading Code Sample...
                                      
                                      
                                      TwilioChat.Web/Scripts/twiliochat.js

                                      Listen to Channel Events

                                      TwilioChat.Web/Scripts/twiliochat.js

                                      The client emits events as well. Let's see how we can listen to those events as well.

                                      Listen to Client Events

                                      Listen to Client Events

                                      Just like with channels, we can register handlers for events on the Client:

                                      • channelAdded: When a channel becomes visible to the Client.
                                      • channelRemoved: When a channel is no longer visible to the Client.
                                      • tokenExpired: When the supplied token expires.
                                      Loading Code Sample...
                                            
                                            
                                            TwilioChat.Web/Scripts/twiliochat.js

                                            Listen to Client Events

                                            TwilioChat.Web/Scripts/twiliochat.js

                                            We've actually got a real chat app going here, but let's make it more interesting with multiple channels.

                                            Create a Channel

                                            Create a Channel

                                            To create a new channel, the user clicks on the "+ Channel" link. That we'll show an input text field where it's possible to type the name of the new channel. The only restriction here, is that the user can't create a channel called "General Channel". Other than that, creating a channel is as simple as calling createChannel with an object that has the friendlyName key. You can create a channel with more options though, see a list of the options here.

                                            Loading Code Sample...
                                                  
                                                  
                                                  TwilioChat.Web/Scripts/twiliochat.js

                                                  Create a Channel

                                                  TwilioChat.Web/Scripts/twiliochat.js

                                                  Next, we will see how we can switch between channels.

                                                  Join Other Channels

                                                  Join Other Channels

                                                  When you tap on the name of a channel from the sidebar, that channel is set as the selectedChannel. The selectChannel method takes care of joining to the selected channel and setting up the selectedChannel.

                                                  Loading Code Sample...
                                                        
                                                        
                                                        TwilioChat.Web/Scripts/twiliochat.js

                                                        Join Other Channels

                                                        TwilioChat.Web/Scripts/twiliochat.js

                                                        At some point your users will want to delete a channel. Let's have a look at how that can be done.

                                                        Delete a Channel

                                                        Delete a Channel

                                                        Deleting a channel is even more simple than creating one. The application lets the user delete the channel they are currently joined to through the "delete current channel" link. The only thing you need to do to actually delete the channel from Twilio, is call the delete method on the channel you are trying to delete. As other methods on the `Channel' object, It'll return a promise where you can set function that is going to handle successes.

                                                        Loading Code Sample...
                                                              
                                                              
                                                              TwilioChat.Web/Scripts/twiliochat.js

                                                              Delete a Channel

                                                              TwilioChat.Web/Scripts/twiliochat.js

                                                              That's it! We've just implemented a simple chat application for C# using ASP.NET MVC.

                                                              Where to Next?

                                                              Where to Next?

                                                              If you are a C# developer working with Twilio, you might want to check out these other tutorials:

                                                              SMS and MMS Notifications

                                                              Never miss another server outage. Learn how to build a server notification system that will alert all administrators via SMS when a server outage occurs.

                                                              Workflow Automation

                                                              Increase your rate of response by automating the workflows that are key to your business. In this tutorial, learn how to build a ready-for-scale automated SMS workflow, for a vacation rental company.

                                                              Masked Phone Numbers

                                                              Protect your users' privacy by anonymously connecting them with Twilio Voice and SMS. Learn how to create disposable phone numbers on-demand, so two users can communicate without exchanging personal information.

                                                              Did this help?

                                                              Thanks for checking out this tutorial! If you have any feedback to share with us, we'd love to hear it. Tweet @twilio to let us know what you think.

                                                              Hector Ortega David Prothero Kat King Andrei Birjukov Andrew Baker Jose Oliveros Jeffrey Linwood Sarah Stringer David Baldassari
                                                              Rate this page:

                                                              Need some help?

                                                              We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd by visiting Twilio's Stack Overflow Collective or browsing the Twilio tag on Stack Overflow.

                                                              Loading Code Sample...
                                                                    
                                                                    
                                                                    

                                                                    Thank you for your feedback!

                                                                    Please select the reason(s) for your feedback. The additional information you provide helps us improve our documentation:

                                                                    Sending your feedback...
                                                                    🎉 Thank you for your feedback!
                                                                    Something went wrong. Please try again.

                                                                    Thanks for your feedback!

                                                                    thanks-feedback-gif