新增项目基础结构与配置,集成 Vue3、Vite、TypeScript、ESLint 等开发环境。实现主页面、样式、图标组件,封装 http 请求,支持 WebView2 与普通浏览器统一 API 调用,便于与 C# 后端通信。完善类型声明与开发文档。
50 lines
1.8 KiB
C#
50 lines
1.8 KiB
C#
using Avalonia_Services.Services;
|
||
using Microsoft.Extensions.DependencyInjection;
|
||
using System;
|
||
using System.Collections.Generic;
|
||
using System.Threading.Tasks;
|
||
|
||
namespace Avalonia_PC.Views
|
||
{
|
||
public partial class MainWindow
|
||
{
|
||
// 路由表:key = 接口路径(忽略大小写),value = 处理方法
|
||
// 新增接口:在此方法中添加一行 _routes["api/xxx"] = ctx => ...
|
||
private Dictionary<string, Func<RouteRequestContext, Task<object?>>> _routes = [];
|
||
|
||
// 服务容器,通过构造函数注入,路由注册时按需解析服务
|
||
private IServiceProvider _services = null!;
|
||
|
||
private void RegisterRoutes()
|
||
{
|
||
var weather = _services.GetRequiredService<WeatherForecastService>();
|
||
// 新增服务示例:var myService = _services.GetRequiredService<MyService>();
|
||
|
||
_routes = new Dictionary<string, Func<RouteRequestContext, Task<object?>>>(StringComparer.OrdinalIgnoreCase)
|
||
{
|
||
["api/getUser"] = _ => GetUserFromDatabaseAsync(),
|
||
["api/processData"] = ctx => ProcessDataAsync(ExtractInput(ctx)),
|
||
["api/wData"] = _ => Task.FromResult<object?>(weather.GetWeatherForecasts()),
|
||
};
|
||
}
|
||
|
||
/// <summary>
|
||
/// 示例:模拟读取用户数据。
|
||
/// </summary>
|
||
private static async Task<object?> GetUserFromDatabaseAsync()
|
||
{
|
||
await Task.Delay(100);
|
||
return new { id = 1, name = "张三", email = "zhangsan@example.com" };
|
||
}
|
||
|
||
/// <summary>
|
||
/// 示例:模拟处理输入数据。
|
||
/// </summary>
|
||
private static async Task<object?> ProcessDataAsync(string? input)
|
||
{
|
||
await Task.Delay(200);
|
||
return $"Processed: {input?.ToUpperInvariant()}";
|
||
}
|
||
}
|
||
}
|