c# - Azure SDK UnauthorizedException : Put token failed. 状态代码 : 401, 状态描述:未经授权:当 KeyName 为空时,资源 URI 必须

标签 c# mqtt azure-iot-hub azure-iot-sdk

使用 C#、Visual Studio 中的 Windows 表单模板和 Microsoft Azure 客户端 SDK

我正在尝试向 IOT 中心发送消息。我使用虚拟 Pi 测试了连接字符串,它在那里工作,我可以在 Azure Shell 中看到连接和传入消息。

进口:

using System.Windows.Forms;
using Microsoft.Azure.Devices;
using Message = Microsoft.Azure.Devices.Message;
static string connectionString = "HostName=****.azure- devices.net;DeviceId=****;SharedAccessKey=*******=";
static string deviceId = "SensorTest";
static ServiceClient serviceClient;

serviceClient = ServiceClient.CreateFromConnectionString(connectionString);
SendMessageToCloud("takemystringyoupieceof***").Wait();


private static async Task SendMessageToCloud(string s)
        {
            MyData data = new MyData
            {
                Thing1 = "string",
                Thing2 = "string",
                Thing3 = 1234,
                Thing4 = "string",
                Thing5 = s
            };

            var serializeData = JsonConvert.SerializeObject(data);
            var commandMessage = new Message(Encoding.ASCII.GetBytes(serializeData));
            await serviceClient.SendAsync(deviceId, commandMessage);
        }

这会引发内部异常:

{"Put token failed. status-code: 401, status-description:
Unauthorized: When KeyName is empty the resource URI must include a device id (Value '****.azure- devices.net').."} 
System.Exception {Microsoft.Azure.Devices.Common.Exceptions.UnauthorizedException}

我需要一些帮助来理解错误消息:

  • 本例中的 KeyName 不是“SharedKey”吗?`
  • 如上所示,设备 ID 已包含在内?
  • 错误消息中的值是主机名的值吗?

对于工作代码示例,myData 类:

internal class MyData
    {
        public string Thing1 { get; set; }
        public string Thing2 { get; internal set; }
        public int Thing3 { get; set; }
        public string Thing4 { get; set; }
        public string Thing5 { get; set; }

    }

最佳答案

您正在将 DeviceClient 连接字符串与 ServiceClient 结合使用。您在 SendMessageToCloud 中调用的 SendAsync 实际上是一个云到设备 API。因此,根据您的意图,答案是您需要使用 DeviceClient(可以在 here 找到有用的示例),或者您想要使用适当的服务连接字符串,该字符串可以在 IoTHub 的共享访问策略边栏选项卡中找到在门户中。实行最小权限,服务 key 允许云到设备消息(有关共享访问策略的详细信息可以在 here 中找到)

关于c# - Azure SDK UnauthorizedException : Put token failed. 状态代码 : 401, 状态描述:未经授权:当 KeyName 为空时,资源 URI 必须,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68085238/

相关文章:

azure - 如何指定到网关的路由

azure - Rust应用程序如何将云到设备的消息发送到旨在到达设备的IoTHub?

c# - 当表单请求导致文件下载时,如何防止按钮按下直到表单请求完成

C# DataGrid 更新所有行

c# - 多人游戏中玩家在服务器上的个人棋盘

c# - 将字典连接到字符串 "key=val&key=val..."

docker - 无法订阅Docker Eclipse-Mosquitto Broker

node.js - 使用相同的 JWT token 进行 MQTT 身份验证

javascript - 只有在大 for 循环结束后才会调用回调

c# - 你调用的对象是空的。使用 TPM 设备客户端发送消息时