.NET Core蓝牙串口连接报错:请求的地址在上下文中无效
修复.NET Core蓝牙SerialPort连接问题
你当前使用BluetoothService.SerialPort枚举创建蓝牙端点时出现「请求的地址在其上下文中无效」错误,虽然SerialPort的UUID确实是00001101-0000-1000-8000-00805F9B34FB,但直接依赖枚举可能存在适配问题,以下是具体修复方案:
核心修复步骤
手动指定UUID创建服务端点
放弃使用BluetoothService.SerialPort枚举,直接用已知的UUID实例化Guid对象来创建BluetoothEndPoint,替换原代码中端点创建的部分:// 替换原BluetoothEndPoint创建代码 Guid serialPortUuid = Guid.Parse("00001101-0000-1000-8000-00805F9B34FB"); BluetoothEndPoint endPoint = new BluetoothEndPoint(selectedDevice.DeviceAddress, serialPortUuid);提前验证设备是否支持SerialPort服务
在尝试连接前,先检查目标设备是否暴露了SerialPort服务,避免无效连接尝试:// 选择设备后添加这段检查代码 Console.WriteLine("Checking for SerialPort service..."); Guid[] supportedServices = selectedDevice.GetServices(); bool hasSerialPortService = supportedServices.Contains(serialPortUuid); if (!hasSerialPortService) { Console.WriteLine("Selected device does not support SerialPort service."); return; }确认权限与配对状态
- Windows系统:确保应用清单中声明了蓝牙访问权限
- Linux系统:运行应用的用户需加入
bluetooth用户组 - 目标设备必须已和当前系统完成配对,未配对设备会直接导致连接失败
完整修复后的代码示例
try { BluetoothClient bluetoothClient = new BluetoothClient(); Console.WriteLine("Scanning for Bluetooth devices..."); BluetoothDeviceInfo[] devices = bluetoothClient.DiscoverDevices(); for (int i = 0; i < devices.Length; i++) { Console.WriteLine($"{i + 1}. {devices[i].DeviceName} ({devices[i].DeviceAddress})"); } Console.Write("Enter the number of the device you want to connect to: "); int deviceIndex = int.Parse(Console.ReadLine()) - 1; if (deviceIndex < 0 || deviceIndex >= devices.Length) { Console.WriteLine("Invalid device number."); return; } BluetoothDeviceInfo selectedDevice = devices[deviceIndex]; Guid serialPortUuid = Guid.Parse("00001101-0000-1000-8000-00805F9B34FB"); Console.WriteLine("Checking for SerialPort service..."); Guid[] supportedServices = selectedDevice.GetServices(); if (!supportedServices.Contains(serialPortUuid)) { Console.WriteLine("Selected device does not support SerialPort service."); return; } Console.WriteLine($"Connecting to {selectedDevice.DeviceName}..."); BluetoothEndPoint endPoint = new BluetoothEndPoint(selectedDevice.DeviceAddress, serialPortUuid); bluetoothClient.Connect(endPoint); Console.WriteLine("Connected successfully!"); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); } catch (Exception ex) { Console.WriteLine($"An error occurred: {ex.Message}"); Console.ReadKey(); }
内容的提问来源于stack exchange,提问作者atwer1276
相关产品推荐
相关产品推荐

