繁体   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

我是 Bazor web 程序集(Blazor 客户端)的新手。

我用 Asp.net 核心 web api 和 ZC31C335EF37283C451B18BA0DD371 创建了一个项目。 为了与 asp.net 核心 web api 和 ZD18B8624A0F5F721DA7B8235 等功能一起使用,可以使用默认功能

添加SpaStaticFiles
使用温泉

如何像 angular 一样使用 Blazor webassembly? 或者如何用 Blazor 客户端替换现有的 Angular SPA?

一些链接为 Blazor 程序集预览提供了解决方案。 但是在最新版本中找不到相同的功能。

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

在此处输入图像描述

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

首先创建这个 HttpObject:

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

然后创建您的库 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);
    }
}  

现在创建您的 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;

}

在 ConfigureServices 方法中的 startup.cs 中声明您的依赖注入:

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

现在,如果你想在一些 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
       }
    }
}

仅此而已。 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