.net8 blazor auto模式很爽(四)改造vs自动创建的Blazor auto为前后端分离模式(3)

BlazorApp1的appsettings改为下面的内容,注意 "BaseAddress": "https://localhost:7228"这个商端口号要和Properties的launchSettings内容一致:

cs 复制代码
{
  "BaseAddress": "https://localhost:7228",
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

修改 BlazorApp1的Program:

cs 复制代码
using BlazorApp1.Client.Pages;
using BlazorApp1.Client.Services;
using BlazorApp1.Components;
using SharedLibrary.Repositories;
using SharedLibrary.Models;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorComponents()
    .AddInteractiveServerComponents()
    .AddInteractiveWebAssemblyComponents();
//新增1*****
//注册控制器服务。这个方法告诉应用程序在启动期间应该注册哪些服务,以便它们可以在整个应用程序中使用。
builder.Services.AddControllers();
//将IWeatherForecastRepository接口与WeatherForecastServices类进行关联。通过这样的注册,应用程序可以使用依赖注入来获取WeatherForecastServices的实例,而不需要直接实例化它。
builder.Services.AddScoped<IWeatherForecastRepository, WeatherForecastServices>();
//创建了一个HttpClient的实例,并将其注册到依赖注入容器中。在BaseAddress属性中设置了一个基本的URI地址,该地址通过配置文件中的BaseAddress键来获取。这样的做法是为了在应用程序的其它部分中可以轻松地使用HttpClient来进行网络请求。
builder.Services.AddScoped(http => new HttpClient
{
    BaseAddress = new Uri(builder.Configuration.GetSection("BaseAddress").Value!)
});
//新增1结束
var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseWebAssemblyDebugging();
}
else
{
    app.UseExceptionHandler("/Error", createScopeForErrors: true);
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
//新增2*****
//配置应用程序以便能够自动将HTTP请求路由到相应的控制器操作方法,为Blazor应用程序提供了更灵活的方式来处理和响应HTTP请求。
app.MapControllers();
//新增2结束
app.UseStaticFiles();
app.UseAntiforgery();

app.MapRazorComponents<App>()
    .AddInteractiveServerRenderMode()
    .AddInteractiveWebAssemblyRenderMode()
    .AddAdditionalAssemblies(typeof(BlazorApp1.Client._Imports).Assembly);

app.Run();

BlazorApp1.Client的Program:

cs 复制代码
using BlazorApp1.Client.Services;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using SharedLibrary.Repositories;

var builder = WebAssemblyHostBuilder.CreateDefault(args);
//增加内容
//将 IWeatherForecastRepository 接口与 WeatherForecastServices 类进行关联,使得应用程序可以通过依赖注入来获取WeatherForecastServices的实例。这样的注册方式允许应用程序在需要时获取与接口相关联的具体实现,而不需要在代码中直接实例化实现类。
builder.Services.AddScoped<IWeatherForecastRepository, WeatherForecastServices>();
//注册了一个 HttpClient 实例到依赖注入容器中。通过使用 BaseAddress 属性,设置了 HttpClient 实例的基本 URI 地址为 builder.HostEnvironment.BaseAddress。
//builder.HostEnvironment.BaseAddress 表示了Blazor应用程序的基本地址,在客户端浏览器中执行时,它通常指向部署应用程序的URL。
//这样的注册方式使得应用程序可以轻松地在客户端使用HttpClient来进行网络请求,并且可以通过依赖注入来管理HttpClient的生命周期和配置。
builder.Services.AddScoped(http => new HttpClient
{
    BaseAddress = new Uri(builder.HostEnvironment.BaseAddress),
});
//增加内容结束
await builder.Build().RunAsync();

BlazorApp1.Client的_Imports:

cs 复制代码
@using System.Net.Http
@using System.Net.Http.Json
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using static Microsoft.AspNetCore.Components.Web.RenderMode
@using Microsoft.AspNetCore.Components.Web.Virtualization
@using Microsoft.JSInterop
@using BlazorApp1.Client
@using SharedLibrary.Models
@using BlazorApp1.Client.Services
@using SharedLibrary.Repositories
@inject IWeatherForecastRepository WeatherForecastServices

运行项目,我们就把Weather成功从前后端分离了:

看起来有些复杂,但是我认为这是必须要做的。可以看到想要前后端进行通信,我们仍然是用的标准api模式。在BlazorApp1建立一个api"WeatherForecastController",然后在BlazorApp1.Client用"WeatherForecastServices"对api进行调用,在SharedLibrary加了"IWeatherForecastRepository"进行前后端的连接。在BlazorApp1.Client的页面中,我们就可以很方便地使用 await WeatherForecastServices.GetWeatherForecastAsync()来获取数据了。

吐槽一下,不如后端建api,前端直接用js调用来得简单。但是呢我们blazor几乎全程使用c#,非常严谨,喜欢就用,不喜欢就拜拜。

相关推荐
1314lay_10072 小时前
.Net 7.0 Core 文件导入接口的实现
visualstudio·c#·.net
贾修行2 小时前
Kestrel:.NET 的高性能 Web 服务器探秘
服务器·前端·kestrel·.net·net core·web-server·asp.net-core
工业甲酰苯胺2 小时前
C#中的多级缓存架构设计与实现深度解析
缓存·c#·wpf
聊聊MES那点事2 小时前
如何在FastReport.NET中自定义就绪报表查看器(Viewer)
.net·报表工具·fastreport
ye902 小时前
C#中的线程Threads与任务Tasks
c#
William_cl2 小时前
C# ASP.NET强类型视图:让 UI 数据交互告别 “猜谜游戏“
ui·c#·asp.net
Traced back11 小时前
# C# + SQL Server 实现自动清理功能的完整方案:按数量与按日期双模式
开发语言·c#
yj爆裂鼓手12 小时前
c#万能变量
开发语言·c#
万物得其道者成12 小时前
UI UX Pro Max: AI 驱动的设计系统生成引擎深度解析
人工智能·ui·ux
不绝19112 小时前
C#进阶:委托
开发语言·c#