简体   繁体   English

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

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

I am new to Bazor web assembly (Blazor Client).我是 Bazor web 程序集(Blazor 客户端)的新手。

I have created a project with Asp.net Core web api with Angular Application.我用 Asp.net 核心 web api 和 ZC31C335EF37283C451B18BA0DD371 创建了一个项目。 In order to work with asp.net core web api and angular, I can use the default functionality like为了与 asp.net 核心 web api 和 ZD18B8624A0F5F721DA7B8235 等功能一起使用,可以使用默认功能

AddSpaStaticFiles添加SpaStaticFiles
UseSpa使用温泉

How can I use Blazor webassembly like the angular?如何像 angular 一样使用 Blazor webassembly? Or How can replace the existing Angular SPA with Blazor Client?或者如何用 Blazor 客户端替换现有的 Angular SPA?

Some links provided a solution for Blazor assembly preview.一些链接为 Blazor 程序集预览提供了解决方案。 But the same functionality not found on the latest.但是在最新版本中找不到相同的功能。

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

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

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. 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 核心后端直接像 MVC 项目。

在此处输入图像描述

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:创建新项目后,您只需使用.Net Core 附带的内置Http 客户端库调用后端端点,或者您可以使用.Net HttpClient 创建自己的库并将其注入您的组件或使用依赖注入的页面,如果你想创建自己的库,请遵循以下过程:

First Create this HttpObject:首先创建这个 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:然后创建您的库 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:现在创建您的 ILibrary 接口并声明实现的方法:

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:在 ConfigureServices 方法中的 startup.cs 中声明您的依赖注入:

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:现在,如果你想在一些 Razor 组件或页面中使用你的库,只需像这样注入它:

@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. 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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM