【问题标题】:Connect asp.net core web api with Blazor Web assembly like Angular SPA将 asp.net core web api 与 Angular SPA 等 Blazor Web 程序集连接起来
【发布时间】:2020-10-26 20:17:27
【问题描述】:

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

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

AddSpaStaticFiles
使用温泉

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

【问题讨论】:

  • 我很确定这是另一种类型的项目。尝试关注this 看看它创造了什么

标签: asp.net asp.net-core single-page-application blazor-client-side blazor-webassembly


【解决方案1】:

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

创建新项目后,您只需简单地使用 .Net Core 附带的内置 Http Client library 调用后端端点,或者您可以使用 .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;

}

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

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-11-18
    • 2020-04-15
    • 2020-07-15
    • 2018-11-30
    • 2018-08-15
    • 2021-11-22
    • 1970-01-01
    • 2019-07-11
    • 1970-01-01
    相关资源
    最近更新 更多