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

相关推荐
ChaITSimpleLove4 小时前
.NET9 实现斐波那契数列(FibonacciSequence)性能测试
.net·性能测试·斐波那契数列·fibonacci·benchmarkdotnet·datadog.trace
葬歌倾城15 小时前
JSON的缩进格式方式和紧凑格式方式
c#·json
Eiceblue16 小时前
使用 C# 发送电子邮件(支持普通文本、HTML 和附件)
开发语言·c#·html·visual studio
小小小小王王王16 小时前
hello判断
开发语言·c#
共享ui设计和前端开发人才17 小时前
UI前端大数据处理安全性保障:数据加密与隐私保护策略
ui
ui设计前端开发老司机17 小时前
UI前端大数据处理性能瓶颈突破:分布式计算框架的应用
ui
前端开发与ui设计的老司机17 小时前
UI前端与数字孪生结合实践探索:智慧物流的货物追踪与配送优化
前端·ui
金增辉18 小时前
基于C#的OPCServer应用开发,引用WtOPCSvr.dll
c#
future141220 小时前
C#学习日记
开发语言·学习·c#
UI设计和前端开发从业者20 小时前
从UI设计到数字孪生实战应用:构建智慧金融的智能风控平台
ui·金融