azureazure-functionsazure-web-app-service

Redirect service (302) in Azure, best possible approach?


I need to create a redirector that redirects user to an external domain while retaining the query params and one additional param.

e.g. When a user visits https://contoso.com/redirect?docId=123, it will redirect the user to https://contoso-v2.com/home?docId=123&token=xxxxxxx

Once user visits https://contoso.com/redirect?docId=123, this endpoint will process the info (from query params) and generate a token that needs to be appended in target URL.

What would be the most efficient and best way in Azure? Writing a simple Azure Web App or is there any better way?


Solution

  • You could use Azure Function with HttpTrigger Binding. With consumption plan the cost would be minimal (1 million invocations are free in pay-as-you-go plan).

    using System.Net;
    
    public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
    {
        log.Info("C# HTTP trigger function processed a request.");
    
        var uri = req.RequestUri;
        var updatedUri = ReplaceHostInUri(uri, "contoso-v2.com");
    
        //return req.CreateResponse(HttpStatusCode.OK, "Original: " + uri + " Updated: " + updatedUri);
        return req.CreateResponse(HttpStatusCode.Found, updatedUri);
    }
    
    private static string ReplaceHostInUri(Uri uri, string newHostName) {
        var builder = new UriBuilder(uri);
    
        builder.Host = newHostName;
        //Do more trasformations e.g. modify path, add more query string vars
    
        return builder.Uri.ToString();
    }