You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何同时从Flutter和ASP.NET向SQL Server插入数据并在ASP.NET控制面板展示

技术实现方案:Flutter + ASP.NET + SQL Server 数据交互与展示

一、整体架构逻辑

  • 核心模式:SQL Server作为统一数据源,ASP.NET同时承担数据API服务(供Flutter和自身调用完成数据插入)和控制面板展示;Flutter完全通过ASP.NET的API与数据库交互,避免直接连接数据库的安全风险。
  • 优势:统一数据校验逻辑,减少重复代码,便于后续维护扩展。

二、数据库层实现

1. 示例数据表设计

创建用于存储两边插入数据的表(以用户操作日志为例):

CREATE TABLE UserLogs (
    Id INT IDENTITY(1,1) PRIMARY KEY,
    Content NVARCHAR(255) NOT NULL,
    Source NVARCHAR(50) NOT NULL, -- 标记数据来源:Flutter/ASP.NET
    CreateTime DATETIME DEFAULT GETDATE()
)

2. ASP.NET数据库连接配置

在项目的appsettings.json中添加SQL Server连接字符串:

"ConnectionStrings": {
    "DefaultConnection": "Server=你的服务器地址;Database=目标库名;User Id=数据库账号;Password=数据库密码;TrustServerCertificate=True;"
}

三、ASP.NET后端实现

1. 数据操作层(EF Core示例)

  • 定义实体类:
public class UserLog
{
    public int Id { get; set; }
    public string Content { get; set; }
    public string Source { get; set; }
    public DateTime CreateTime { get; set; }
}
  • 创建DbContext:
public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
    public DbSet<UserLog> UserLogs { get; set; }
}
  • 在Program.cs中注册DbContext:
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

2. 数据交互API实现

创建LogsController提供插入和查询接口:

[ApiController]
[Route("api/[controller]")]
public class LogsController : ControllerBase
{
    private readonly AppDbContext _dbContext;

    public LogsController(AppDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    // 插入数据接口(Flutter和ASP.NET自身均可调用)
    [HttpPost]
    public async Task<IActionResult> AddLog([FromBody] UserLog log)
    {
        if (string.IsNullOrEmpty(log.Content) || string.IsNullOrEmpty(log.Source))
            return BadRequest("内容和来源不能为空");
        
        _dbContext.UserLogs.Add(log);
        await _dbContext.SaveChangesAsync();
        return Ok(log.Id);
    }

    // 查询所有数据接口(供控制面板展示用)
    [HttpGet]
    public async Task<IActionResult> GetAllLogs()
    {
        var logs = await _dbContext.UserLogs.OrderByDescending(l => l.CreateTime).ToListAsync();
        return Ok(logs);
    }
}

3. ASP.NET控制面板实现(Razor Pages示例)

  • 页面逻辑类(Logs.cshtml.cs):
public class LogsModel : PageModel
{
    private readonly AppDbContext _dbContext;
    public List<UserLog> Logs { get; set; }

    public LogsModel(AppDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public async Task OnGetAsync()
    {
        Logs = await _dbContext.UserLogs.OrderByDescending(l => l.CreateTime).ToListAsync();
    }
}
  • 页面视图(Logs.cshtml):
@page
@model LogsModel
@{
    ViewData["Title"] = "数据控制面板";
}

<h1>所有数据记录</h1>

<table class="table">
    <thead>
        <tr>
            <th>ID</th>
            <th>内容</th>
            <th>来源</th>
            <th>创建时间</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var log in Model.Logs)
        {
            <tr>
                <td>@log.Id</td>
                <td>@log.Content</td>
                <td><strong>@log.Source</strong></td>
                <td>@log.CreateTime.ToString("yyyy-MM-dd HH:mm:ss")</td>
            </tr>
        }
    </tbody>
</table>
  • ASP.NET自身插入数据:在业务逻辑中直接调用AddLog方法,或者通过HTTP请求调用自身API。

四、Flutter端数据插入实现

1. 依赖配置

在pubspec.yaml中添加网络请求依赖:

dependencies:
  http: ^1.1.0

2. 数据插入方法实现

创建工具方法调用ASP.NET的API:

import 'package:http/http.dart' as http;
import 'dart:convert';

Future<int?> addLogToServer(String content) async {
  final url = Uri.parse('http://你的ASP.NET服务器地址/api/logs');
  final response = await http.post(
    url,
    headers: {'Content-Type': 'application/json'},
    body: jsonEncode({
      'content': content,
      'source': 'Flutter',
      'createTime': DateTime.now().toIso8601String()
    }),
  );

  if (response.statusCode == 200) {
    return int.parse(response.body);
  } else {
    // 处理请求失败逻辑
    return null;
  }
}
  • 页面调用示例:
ElevatedButton(
  onPressed: () async {
    await addLogToServer('Flutter端插入的测试数据');
    // 提示用户插入成功
  },
  child: const Text('插入数据'),
)

五、关键注意事项

  • 跨域配置:ASP.NET需开启CORS允许Flutter访问,在Program.cs中添加:
    builder.Services.AddCors(options =>
    {
        options.AddPolicy("AllowFlutter",
            policy => policy.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
    });
    // 在app.UseRouting()后添加
    app.UseCors("AllowFlutter");
    
  • 安全防护:禁止在Flutter端硬编码数据库凭证;可为API添加JWT身份验证,拦截非法请求。
  • 数据校验:在ASP.NET的API层统一校验数据合法性,避免脏数据入库。
  • 部署注意:ASP.NET项目部署到服务器后,需确保SQL Server防火墙允许服务器IP访问;Flutter端测试环境用本地IP,生产环境切换为服务器域名。

内容的提问来源于stack exchange,提问作者نادر البراهمه

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 10:52:03