Jeeva J
Jeeva J

Reputation: 3253

Connect asp.net core web api with Blazor Web assembly like Angular SPA

I am new to Bazor web assembly (Blazor Client).

I have created a project with Asp.net Core web api with Angular Application. In order to work with asp.net core web api and angular, I can use the default functionality like

AddSpaStaticFiles
UseSpa

How can I use Blazor webassembly like the angular? Or How can replace the existing Angular SPA with Blazor Client?

Some links provided a solution for Blazor assembly preview. But the same functionality not found on the latest.

https://csharp.christiannagel.com/2019/08/27/blazorserverandclient/

    app.UseClientSideBlazorFiles<Client.Startup>();
 
    app.UseEndpoints(endpoints =>
    {
      endpoints.MapDefaultControllerRoute();
      endpoints.MapFallbackToClientSideBlazor<Client.Startup>("index.html");
    });

Upvotes: 1

Views: 1468

Answers (1)

Elsavies
Elsavies

Reputation: 64

Remember that Web Assembly Apps are created to work like another SPA like Angular or React, it means that you create your view presentation or Blazor Web Assembly App in a independent project, then you get the data from some Web Service, for example an Rest API made in .Net Core 3.1, to create the Blazor Web Assembly Project you just go to File -> New -> Project -> Blazor App -> Blazor WebAssembly App, do not choose ASP.NET Core Hosted option, this will attach your project to the .net core backend directly like an MVC Project.

enter image description here

After having your new project created, you just simple need to call your backend end-points with the Built-In Http Client library that comes with .Net Core or you can create your own library using .Net HttpClient and Inject it in your components or pages using Dependency Injection, if you want to create your own library, follow this process:

First Create this HttpObject:

public class HttpResultObject<T>
    {
        public bool IsSuccessful { get; set; }
        public HttpStatusCode HttpResultCode { get; set; }        
        public T Result { get; set; }
    }

Then create your Library Class:

public class MyLibrary : IMyLibrary
{
    public string GetApiUri(string server)
    {
              
         if (server.Equals("auth"))
             return "https://localhost:8080/api/";
            
             return "https://localhost:8080/api/";
    }
    
    //Http Get Method Example
    public async Task<HttpResultObject<U>> SetAppMethodGetParametersAsync<U>(string server, string method, Dictionary<string, object> parameters, CancellationToken token) where U : class 
    { 
         string getParameters = string.Empty;
    
         foreach(var p in parameters)
         {
              if (p.Value.GetType() == typeof(string))
                  getParameters = getParameters.Equals(string.Empty) ? "?" + p.Value.ToString() : "&" + p.Value.ToString();
         }
    
         var uri = new System.Uri(GetApiUri(server) + method + "/" + getParameters) ;                       
    
         var response = await CallAppMethodGetAsync(uri, token);           
    
         var result = new HttpResultObject<U>()
         {
             IsSuccessful = response.IsSuccessStatusCode,
             HttpResultCode = response.StatusCode,                
             Result = JsonSerializer.Deserialize<U>(response?.Content?.ReadAsStringAsync()?.Result)
         };         
    
         return result;
    }

    private async Task<HttpResponseMessage> CallAppMethodGetAsync(System.Uri uri, CancellationToken token)
    {
        Console.WriteLine(uri.ToString());

        HttpStatusCode responseStatus = HttpStatusCode.BadRequest;
        try
        {                
            HttpClient client = new HttpClient
            {
                Timeout = TimeSpan.FromMilliseconds(240000)
            };

            HttpResponseMessage response = new HttpResponseMessage(responseStatus);
            HttpRequestMessage request = new HttpRequestMessage()
            {
                RequestUri = uri,                  
                Method = HttpMethod.Get
            };

            var authToken = this.GetLocalStorageItem("authToken");                

            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            if (authToken != null && authToken.GetType() == typeof(string))                                    
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Convert.ToString(authToken));                

            token.ThrowIfCancellationRequested();

            response = await client.SendAsync(request, token);

            responseStatus = response == null ? HttpStatusCode.BadRequest : response.StatusCode;

            if (response != null && responseStatus != HttpStatusCode.OK && responseStatus != HttpStatusCode.Accepted)
            {

                HttpResponseMessage result = new HttpResponseMessage(responseStatus)
                {
                    Content = new StringContent(response.Content?.ReadAsStringAsync()?.Result, Encoding.UTF8, "application/json")
                };


                return response;
            }

            return response;
        }
        catch (WebException webException)
        {

        }
        catch (System.Net.Sockets.SocketException socketException)
        {

        }
        catch (HttpRequestException httpRequestException)
        {

        }
        catch (ArgumentException argumentException)
        {

        }
        catch (System.Exception exception)
        {

        }

        return new HttpResponseMessage(responseStatus);
    }
}  

Now create your ILibrary Interface and declare the Implemented Methods:

public interface IMyLibrary
{

     string GetApiUri(string server);

     Task<HttpResultObject<U>> SetAppMethodGetParametersAsync<U>(string server, string method, Dictionary<string, object> parameters, CancellationToken token) where U : class;

}

Declare your Dependency Injection in your startup.cs in the ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<IMyLibrary, MyLibrary>();
}

Now, if you want to you use your library in some Razor Component or Page just inject it like this:

@inject IMyLibrary  _myLibrary

@code
{

    private async Task MyHttpGetCall()
    {  
       var cts = new CancellationTokenSource();
        
       var result = await _myLibrary.SetAppMethodPostParametersAsync<HttpResultObject<MyCustomObject>>("auth", new Dictionary<string, object>(), cts.Token);

       if (result.IsSuccesful)
       { 
          //whatever you want to do
       }
    }
}

And that is all!, those are the 2 ways to connect your front-end web site developed with Blazor Web Assembly App to your Backend the same way you does with Angular or React.

Upvotes: 2

Related Questions