如何将Xamarin应用注册页连接到Azure Database for MySQL
Xamarin注册页对接Azure Database for MySQL实现指南
1 创建Azure Database for MySQL实例
- 进入Azure门户,搜索并选择「Azure Database for MySQL 灵活服务器」,点击创建
- 基础信息页配置:
- 选择对应订阅和资源组,自定义服务器名称,选择就近区域
- MySQL版本选8.0,设置管理员账号和密码,记住这组凭证后续要用到
- 网络页配置:
- 访问方式选「公共访问」
- 防火墙规则添加你本地开发设备的公网IP,同时勾选「允许Azure服务和资源访问此服务器」
- 点击「审核+创建」,等待实例部署完成后,在实例详情的「连接字符串」页复制对应连接信息,替换为你自己的管理员密码。
注意:绝对不要将数据库连接凭证硬编码到Xamarin客户端代码中,避免反编译泄露数据引发安全问题,客户端与数据库之间必须通过API层做中转。
2 搭建中转API层
推荐用ASP.NET Core Web API搭建接口,负责接收Xamarin端的注册请求,再写入MySQL数据库:
2.1 安装依赖
在API项目中安装MySqlConnectorNuGet包,用于连接MySQL数据库。
2.2 配置连接字符串
在appsettings.json中添加连接配置:
"ConnectionStrings": { "MySqlConn": "server=你的Azure MySQL服务器地址;port=3306;database=你创建的库名;user=管理员账号;password=管理员密码;SslMode=Required" }
2.3 编写注册接口
首先定义用户模型:
public class UserRegisterRequest { public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } public string Password { get; set; } }
然后编写控制器接口:
[ApiController] [Route("api/[controller]")] public class UserController : ControllerBase { private readonly IConfiguration _config; public UserController(IConfiguration config) { _config = config; } [HttpPost("register")] public async Task<IActionResult> Register([FromBody] UserRegisterRequest request) { // 校验参数逻辑可自行补充 var connStr = _config.GetConnectionString("MySqlConn"); await using var conn = new MySqlConnection(connStr); await conn.OpenAsync(); // 密码要做哈希存储,不要明文存库,这里仅做示例 var sql = "INSERT INTO Users (FirstName, LastName, Email, Password) VALUES (@FirstName, @LastName, @Email, @Password)"; var count = await conn.ExecuteAsync(sql, new { request.FirstName, request.LastName, request.Email, Password = BCrypt.Net.BCrypt.HashPassword(request.Password) }); return count > 0 ? Ok("注册成功") : BadRequest("注册失败"); } }
你可以将这个API部署到Azure App Service,也可以本地调试使用。
3 修改Xamarin注册页代码
3.1 修改RegistrationPage.XAML
给所有输入控件添加x:Name属性,方便后台获取输入值:
<?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="VeggiesUI.Views.RegistrationPage" Shell.NavBarIsVisible="False" Title="Registration" BackgroundImageSource="OIP.jpg"> <StackLayout Margin="20,30,20,0" > <Entry x:Name="FirstNameEntry" Placeholder="Enter First Name" MaxLength="30" Margin="5,0,5,10"/> <Entry x:Name="LastNameEntry" Placeholder="Enter Last Name" MaxLength="30" Margin="5,0,5,10"/> <Entry x:Name="EmailEntry" Placeholder="Enter Email" MaxLength="30" Margin="5,0,5,10"/> <Entry x:Name="PasswordEntry" Placeholder="Enter Password" MaxLength="15" IsPassword="True" Margin="5,0,5,10"/> <Entry x:Name="ConfirmPasswordEntry" Placeholder="Confirm Password" MaxLength="15" IsPassword="True" Margin="5,0,5,5"/> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="0.10*" /> <ColumnDefinition Width="0.90*" /> </Grid.ColumnDefinitions> <CheckBox x:Name="TsCsCheckBox" IsChecked="False"></CheckBox> <Label Grid.Column="1" Text=" Accept Ts and Cs." Margin="0,5,5,0"/> </Grid> <Grid ColumnDefinitions="*,*"> <Button Text="Register" Clicked="OnSaveButtonClicked" BackgroundColor="LightGreen" TextColor="Black" Margin="0,10,5,0"/> <Button Grid.Column="1" Text="Clear" BackgroundColor="LightGreen" TextColor="Black" Clicked="OnDeleteButtonClicked" Margin="0,10,5,0"/> </Grid> <Button Text="Login Instead" Clicked="OnButtonClicked" TextColor="Blue" BackgroundColor="Transparent" BorderWidth="0" CornerRadius="0" WidthRequest="150" FontSize="Medium" /> </StackLayout> </ContentPage>
3.2 修改RegistrationPage.XAML.cs
实现注册提交和清空逻辑,通过HttpClient调用API接口:
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Text.Json; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace VeggiesUI.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class RegistrationPage : ContentPage { // 替换为你自己的API部署地址 private const string ApiBaseUrl = "你的API地址"; private readonly HttpClient _httpClient; public RegistrationPage() { InitializeComponent(); _httpClient = new HttpClient(); } private async void OnSaveButtonClicked(object sender, EventArgs e) { // 基础参数校验 if (string.IsNullOrWhiteSpace(FirstNameEntry.Text) || string.IsNullOrWhiteSpace(LastNameEntry.Text) || string.IsNullOrWhiteSpace(EmailEntry.Text) || string.IsNullOrWhiteSpace(PasswordEntry.Text) || string.IsNullOrWhiteSpace(ConfirmPasswordEntry.Text)) { await DisplayAlert("提示", "请填写所有必填项", "确定"); return; } if (PasswordEntry.Text != ConfirmPasswordEntry.Text) { await DisplayAlert("提示", "两次输入的密码不一致", "确定"); return; } if (!TsCsCheckBox.IsChecked) { await DisplayAlert("提示", "请同意条款", "确定"); return; } try { var registerRequest = new { FirstName = FirstNameEntry.Text.Trim(), LastName = LastNameEntry.Text.Trim(), Email = EmailEntry.Text.Trim(), Password = PasswordEntry.Text }; var json = JsonSerializer.Serialize(registerRequest); var content = new StringContent(json, Encoding.UTF8, "application/json"); var response = await _httpClient.PostAsync($"{ApiBaseUrl}/api/user/register", content); if (response.IsSuccessStatusCode) { await DisplayAlert("提示", "注册成功", "确定"); await Shell.Current.GoToAsync("//LoginPage"); } else { var errorMsg = await response.Content.ReadAsStringAsync(); await DisplayAlert("错误", $"注册失败:{errorMsg}", "确定"); } } catch (Exception ex) { await DisplayAlert("错误", $"请求失败:{ex.Message}", "确定"); } } private void OnDeleteButtonClicked(object sender, EventArgs e) { // 清空所有输入 FirstNameEntry.Text = string.Empty; LastNameEntry.Text = string.Empty; EmailEntry.Text = string.Empty; PasswordEntry.Text = string.Empty; ConfirmPasswordEntry.Text = string.Empty; TsCsCheckBox.IsChecked = false; } private async void OnButtonClicked(object sender, EventArgs e) { await Shell.Current.GoToAsync("//LoginPage"); } } }
4 架构参考

内容的提问来源于stack exchange,提问作者Roopan Jaulin
相关产品推荐
相关产品推荐

