0

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

我已经使用带有 Angular 应用程序的 Asp.net Core web api 创建了一个项目。为了使用 asp.net core web api 和 angular,我可以使用默认功能,例如

AddSpaStaticFiles
UseSpa

如何像 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");
    });
4

1 回答 1

2

请记住,创建 Web 组装应用程序是为了像 Angular 或 React 等其他 SPA 一样工作,这意味着您在独立项目中创建视图演示或 Blazor Web 组装应用程序,然后从某些 Web 服务(例如 Rest API)获取数据在 .Net Core 3.1 中制作,要创建 Blazor Web Assembly 项目,您只需转到 File -> New -> Project -> Blazor App -> Blazor WebAssembly App,不要选择 ASP.NET Core Hosted 选项,这将附加您的项目像 MVC 项目一样直接到 .net 核心后端。

在此处输入图像描述

创建新项目后,您只需简单地使用 .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; }
    }

然后创建您的库类:

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
       }
    }
}

仅此而已!这些是将使用 Blazor Web Assembly 应用程序开发的前端网站连接到后端的两种方法,就像使用 Angular 或 React 一样。

于 2020-07-14T02:42:19.840 回答