Wednesday, January 16, 2019

how to improve the Azure web api call with Token Cache?

if you develop an application with heavy traffic to Azure web api. you should have the cache mechanism to reduce the around trip for token, usually the token will not expire in short peroid.


here i will show a trick to cache the Azure Token with the Token Cache from .net framework.


 private static async Task<string> GetAzureTokenFromCache(string resourceUrl, string clientId, string clientKey) {
            string token = string.Empty;
            if (tokenCache.Count > 0)
            {
                System.Collections.Generic.IEnumerable<TokenCacheItem> List = tokenCache.ReadItems();

                foreach (var value in List)
                {
                
                         if (value.ExpiresOn < DateTime.UtcNow.AddMinutes(60) || String.IsNullOrEmpty(value.AccessToken) || !IsJwtTokenValid(value.AccessToken))
                        {
                            tokenCache.DeleteItem(value);
                            token = await GetAzureToken(resourceUrl,clientId, clientKey);
                        }
                        else
                            token = value.AccessToken;
                    }
                }
                if (String.IsNullOrEmpty(token)) {
                    token = await GetAzureToken(resourceUrl, clientId, clientKey);
                }
            return token;
        }

        private static async Task<string> GetAzureToken(string resourceUrl,string clientId, string key)
        {
            ClientCredential clientCred = new ClientCredential(clientId, key);
            AuthenticationContext authContext = null;
            AuthenticationResult result = null;
            authContext = new AuthenticationContext("https://login.microsoftonline.com/scimdm.onmicrosoft.com",false, tokenCache);
            result = await authContext.AcquireTokenAsync(resourceUrl, clientCred);
                return result.AccessToken ?? "";
            }
        }

how to use the resource file from other page in ASP.Net web application

we can localize the web application with the resource file from Visual studio. Visual studio automaticaly generate the resource file under this folder.

c:\projectfolder\App_LocalResources

in the page level we can use the key in the resource to reference the content.

<asp:Literal runat="server" Text="<%$ Resources:MyKey %>" />

if we want to use this content in other pages.

we can simply follow the steps below

1. add the reference to the resource namespace, you can find the namespace from the design.cs file.

<%@ Import Namespace="Resources.UserControls" %>



2. add the following line to your page which have a reference to the resource file and key.

<%=MyOtherPage_ascx.MyOtherKey %>