How to call token based web api in Blazor


Here is the syntax for calling taken based web api in Blazor server or webassembly.

using MyFleetApp.Data.Model;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;


namespace MyFleetApp.Data.Service
{
    public class InvoiceSearchService : IInvoiceSerach
    {
        private readonly HttpClient httpClient;
        public InvoiceSearchService(HttpClient httpClient)
        {
            this.httpClient = httpClient;
        }
       

        public async Task<Rootobject> GetInvoices(Rootobject objParameter)
        {
            httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", objParameter.token);
            var result = await httpClient.PostAsJsonAsync<Rootobject>("Web API URL will be here", objParameter);
            Rootobject objInvoice = new Rootobject();
            if (result.IsSuccessStatusCode)
            {
                objInvoice = await result.Content.ReadFromJsonAsync<Rootobject>();
            }

            return objInvoice;
        }
    }
}

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.