Is it possible to convert this JS code into .NET?

Joined
Oct 19, 2022
Messages
1
Reaction score
0
I really need help and i would apreciate if someone can help me with this I need to do the same than here but with .NET, instead of node js. I never worked with .NET before.

Is my first time working with tokens and APIs. So i kinda need help with this

Question: Is it possible to do this with .NET? if it's not possible, i would like to know it. thanks.

UH API Behavior - Error handling

. Sample API request with retry for refreshing the token (if the app is using axios and MSAL.js).

Code:
get: async (url, retry = true) => {

        const _url = url;

        const headers = {

            Authorization: `Bearer ${sessionStorage.getItem("user_token")}`

        };

        const _retry = retry;

        const axiosInstance = axios.create({

            headers,

            responseType: "application/json"

        });

        axiosInstance.interceptors.response.use(

            (res) => {                return res;

            },

            async (error) => {

                // debugger;

                const status = error.response ? error.response.status : null;

                if (status === 401 && _retry) {

                    sessionStorage.removeItem("user_token");

              const hasToken = await  refreshToken();                 

                        return httpClirefreshTokenentServiceWithRefreshToken.get(

                            _url,

                            false

                        );                   

                }

                return Promise.reject(error);

            }

        );

        return new Promise((resolve, reject) => {

            axiosInstance

                .get(_url)

                // .post(url, data, headers)

                .then((response) => {

                    if (response.status === 200) {

                        resolve(response.data);

                    } else {

                        resolve(response);

                    }

                })

                .catch((e) => {

                    reject(e);

                });

        });

    },
 
Joined
Mar 10, 2023
Messages
1
Reaction score
0
Code:
Imports System.Net.Http
Imports System.Net.Http.Headers
Imports Microsoft.Identity.Client

Public Class Form1

    Private msalClient As PublicClientApplication
    Private accessToken As String

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ' Initialize MSAL.NET client
        Dim msalConfig As New PublicClientApplicationOptions()
        msalConfig.ClientId = "your_client_id"
        msalConfig.Authority = "https://login.microsoftonline.com/your_tenant_id"
        msalClient = New PublicClientApplication(msalConfig)

        ' Load access token from session storage if it exists
        If Not String.IsNullOrEmpty(sessionStorage.GetItem("access_token")) Then
            accessToken = sessionStorage.GetItem("access_token")
        End If
    End Sub

    Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim url As String = "https://example.com/api/data"

        Try
            Dim result As String = Await GetAsync(url)
            MessageBox.Show("Request succeeded. Response: " & result)
        Catch ex As Exception
            MessageBox.Show("Request failed. Error message: " & ex.Message)
        End Try
    End Sub

    Public Async Function GetAsync(url As String) As Task(Of String)
        Dim headers As New Dictionary(Of String, String)()
        headers("Authorization") = "Bearer " & accessToken

        Dim httpClient As New HttpClient()
        httpClient.DefaultRequestHeaders.Authorization = New AuthenticationHeaderValue("Bearer", accessToken)

        Try
            Dim response As HttpResponseMessage = Await httpClient.GetAsync(url)

            If response.IsSuccessStatusCode Then
                Dim content As String = Await response.Content.ReadAsStringAsync()
                Return content
            Else
                Dim statusCode As Integer = response.StatusCode
                If statusCode = 401 Then
                    Dim hasToken As Boolean = Await RefreshTokenAsync()

                    If hasToken Then
                        Return Await GetAsync(url)
                    End If
                End If
                Throw New HttpRequestException($"HTTP request failed with status code {statusCode}")
            End If
        Catch ex As Exception
            If ex.InnerException IsNot Nothing AndAlso TypeOf ex.InnerException Is HttpRequestException Then
                Dim statusCode As Integer = DirectCast(ex.InnerException, HttpRequestException).StatusCode
                If statusCode = 401 Then
                    Dim hasToken As Boolean = Await RefreshTokenAsync()

                    If hasToken Then
                        Return Await GetAsync(url)
                    End If
                End If
                Throw New HttpRequestException($"HTTP request failed with status code {statusCode}")
            Else
                Throw ex
            End If
        End Try
    End Function

    Private Async Function RefreshTokenAsync() As Task(Of Boolean)
        Try
            Dim authResult As AuthenticationResult = Await msalClient.AcquireTokenSilent({
                "your_api_scopes"
            }).ExecuteAsync()
            accessToken = authResult.AccessToken
            sessionStorage.SetItem("access_token", accessToken)
            Return True
        Catch ex As Exception
            Console.Error.WriteLine("Error refreshing access token: " & ex.Message)
            Return False
        End Try
    End Function

End Class
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top