cancel
Showing results for 
Search instead for 
Did you mean: 
wyattdave

1 Minute Fixes - Handling 302 Redirect urls

Power Automate does not handle 302 redirects out of the box like other web clients do.

 

A 302 redirect is when an API replies with a url that it expects you to then follow. A 301 is a permanent redirect (e.g change or url when rebranded) and a 302 is temporary (often for security).

 

The only way I have seen to handle it is to catch the exception and then use the redirect url in a new http call (the url is normally returned in the Location header). 

wyattdave_0-1708803057681.png

 

 

But this is not great if you want to scale out the connection (and let's be honest it's a little janky). To do it properly we need a custom connector, but guess what, they don't handle them either. Luckily there is a way, and thats so use some custom code.

 

wyattdave_1-1708801522050.png

 

The code will automatically follow the redirect url and pass on the response.

 

 

 

public class Script : ScriptBase
{
  public override async Task<HttpResponseMessage> ExecuteAsync()
{
    // Use the context to forward/send an HTTP request
    HttpResponseMessage response = await this.Context.SendAsync(this.Context.Request, this.CancellationToken).ConfigureAwait(false);
    // Check if the response is a 302 redirect
    if (response.StatusCode == HttpStatusCode.Found)
    {
        // If has Loocation Header extract the redirect URL from the Location header
        if (response.Headers.Location != null)
        {
            var redirectUrl = response.Headers.Location.ToString();     
            // Create a new request with the redirect URL
            var redirectRequest = new HttpRequestMessage(HttpMethod.Get, redirectUrl);
            // Forward the new request to the redirect URL
            response = await this.Context.SendAsync(redirectRequest, this.CancellationToken).ConfigureAwait(true);
        }
        else
        {
            // If the Location header is not present, return an error response
            response = new HttpResponseMessage(HttpStatusCode.BadRequest);
            response.Content = CreateJsonContent("Location header missing in the redirect response.");
        }
    }
    else if (response.IsSuccessStatusCode)
    {
        // If the response is successful, perform any necessary transformations
        var responseString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
        // Example case: response string is some JSON object
        var result = JObject.Parse(responseString);  
        // Wrap the original JSON object into a new JSON object with just one key ('wrapped')
        var newResult = new JObject
        {
            ["wrapped"] = result,
        };    
        response.Content = CreateJsonContent(newResult.ToString());
    }
    return response;
}
}

 

 

 

And that's it, it should work on any api and means your custom connector will act like one api call and not need exception handling.


>----------------------------------------------------------------------------------------------------------------------------------------------
This is a series of short blogs designed to help find solutions for random problems before you ask, keep your eyes out for more

l also do long form and broader Power Platform blogs here https://dev.to/wyattdave

About the Author
  • Experienced Consultant with a demonstrated history of working in the information technology and services industry. Skilled in Office 365, Azure, SharePoint Online, PowerShell, Nintex, K2, SharePoint Designer workflow automation, PowerApps, Microsoft Flow, PowerShell, Active Directory, Operating Systems, Networking, and JavaScript. Strong consulting professional with a Bachelor of Engineering (B.E.) focused in Information Technology from Mumbai University.
  • I am a Microsoft Business Applications MVP and a Senior Manager at EY. I am a technology enthusiast and problem solver. I work/speak/blog/Vlog on Microsoft technology, including Office 365, Power Apps, Power Automate, SharePoint, and Teams Etc. I am helping global clients on Power Platform adoption and empowering them with Power Platform possibilities, capabilities, and easiness. I am a leader of the Houston Power Platform User Group and Power Automate community superuser. I love traveling , exploring new places, and meeting people from different cultures.
  • Read more about me and my achievements at: https://ganeshsanapblogs.wordpress.com/about MCT | SharePoint, Microsoft 365 and Power Platform Consultant | Contributor on SharePoint StackExchange, MSFT Techcommunity
  • Encodian Owner / Founder - Ex Microsoft Consulting Services - Architect / Developer - 20 years in SharePoint - PowerPlatform Fan
  • Founder of SKILLFUL SARDINE, a company focused on productivity and the Power Platform. You can find me on LinkedIn: https://linkedin.com/in/manueltgomes and twitter http://twitter.com/manueltgomes. I also write at https://www.manueltgomes.com, so if you want some Power Automate, SharePoint or Power Apps content I'm your guy 🙂
  • I am the Owner/Principal Architect at Don't Pa..Panic Consulting. I've been working in the information technology industry for over 30 years, and have played key roles in several enterprise SharePoint architectural design review, Intranet deployment, application development, and migration projects. I've been a Microsoft Most Valuable Professional (MVP) 15 consecutive years and am also a Microsoft Certified SharePoint Masters (MCSM) since 2013.
  • Big fan of Power Platform technologies and implemented many solutions.
  • Passionate #Programmer #SharePoint #SPFx #M365 #Power Platform| Microsoft MVP | SharePoint StackOverflow, Github, PnP contributor
  • Web site – https://kamdaryash.wordpress.com Youtube channel - https://www.youtube.com/channel/UCM149rFkLNgerSvgDVeYTZQ/