.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#,非常严谨,喜欢就用,不喜欢就拜拜。

相关推荐
追逐时光者6 小时前
.NET 使用 MethodTimer 进行运行耗时统计提升代码的整洁性与可维护性!
后端·.net
CallZhang2109 小时前
Vision Master的C#脚本与opencv联合编程
opencv·计算机视觉·c#·视觉检测
AI视觉网奇9 小时前
kafka 冲突解决 kafka安装
c#·linq
hqwest10 小时前
C#WPF实战出真汁07--【系统设置】--菜品类型设置
开发语言·c#·wpf·grid设计·stackpanel布局
萘柰奈10 小时前
Unity进阶--C#补充知识点--【Unity跨平台的原理】Mono与IL2CPP
unity·c#·游戏引擎
程序设计实验室11 小时前
StarBlog v1.3.0 新版本,一大波更新以及迁移服务器部署
c#·aspnetcore·starblog番外
淡海水11 小时前
【原理】Struct 和 Class 辨析
开发语言·c++·c#·struct·class
淡海水11 小时前
【原理】Unity GC 对比 C# GC
unity·c#·gc·垃圾回收
张人玉12 小时前
C#读取文件, IO 类属性及使用示例
microsoft·c#
许泽宇的技术分享13 小时前
Windows桌面自动化的革命性突破:深度解析Windows-MCP.Net Desktop模块的技术奥秘
windows·自动化·.net