【问题标题】:How to create a RabbitMQ user using the RabbitMQ API from a c# console app如何使用来自 c# 控制台应用程序的 RabbitMQ API 创建 RabbitMQ 用户
【发布时间】:2020-08-21 13:21:54
【问题描述】:

我正在开发一个用 C# 编写的 Hashicorp Vault 管理 .net-core 3.1.3 控制台应用程序。我的任务是使用 RabbitMQ restful API 从控制台应用程序在 MQ 服务器上创建 RabbitMQ 用户。我对这个 API 的经验为零。我一直在阅读文档,但仍然不知道如何开始。 一般来说,我对 API 的经验有限,并且从未尝试从控制台应用程序中执行此类操作。 任何指导或示例代码将不胜感激。 干杯。 马特

【问题讨论】:

  • 进度:已安装 curl nuget。现在就开始试验。
  • 进展:使用内置 HttpClient。

标签: c# asp.net-core .net-core rabbitmq console-application


【解决方案1】:

您需要 RabbitMQ 管理 HTTP API,其文档为 here。具体来说,您需要 PUT /api/users/name 端点上的用户。

在 C# 中发出 HTTP 请求的方法有很多,最简单的可能是 WebRequest 类,如文档 here 所述。您需要set the method to PUTwrite your json payload to the requestset your rabbitmq credentials for the request

【讨论】:

【解决方案2】:

感谢线索蝙蝠亚当。这是我最终的结果,并且效果很好。

try
{
    // Set MQ server credentials
    NetworkCredential networkCredential = new NetworkCredential("mqUserName", "mqPassword");

    // Instantiate HttpClientHandler, passing in the NetworkCredential
    HttpClientHandler httpClientHandler = new HttpClientHandler { Credentials = networkCredential };

    // Instantiate HttpClient passing in the HttpClientHandler
    using HttpClient httpClient = new HttpClient(httpClientHandler);

    // Get the response from the API endpoint.
    HttpResponseMessage httpResponseMessage = await httpClient.GetAsync("http://YourServer:AndPort/api/users/");

    // Get the response content.
    HttpContent httpContent = httpResponseMessage.Content;

    // Get the stream of the content.
    using StreamReader streamReader = new StreamReader(await httpContent.ReadAsStreamAsync());

    // Get the output string.
    string returnedJsonString = await streamReader.ReadToEndAsync();

    // Instantiate a list to loop through.
    List<string> mqAccountNames = new List<string>();

    if (returnedJsonString != "")
    {
        // Deserialize into object
        dynamic dynamicJson = JsonConvert.DeserializeObject(returnedJsonString);
        if (dynamicJson != null)
        {
            foreach (dynamic item in dynamicJson)
            {
                mqAccountNames.Add(item.name.ToString());
            }
        }
    }

    bool accountExists = false;

    foreach (string mqAccountName in mqAccountNames)
    {
        if (mqAccountName == userName)
        {
            accountExists = true;
        }
    }

    switch (accountExists)
    {
        case true:
            Console.WriteLine("This user already exists on the MQ server.");
            break;
        case false:
            // Create the new user on the MQ Server
            Console.WriteLine("This user will be created on the MQ server.");
                        
            string uri = $"http://YourServer:AndPort/api/users/{userName}";

            MqUser mqUser = new MqUser
            {
                password = password,
                tags = "administrator"
            };

            string info = JsonConvert.SerializeObject(mqUser);
            StringContent content = new StringContent(info, Encoding.UTF8, "application/json");

            httpResponseMessage = await httpClient.PutAsync(uri, content);
            if (!httpResponseMessage.IsSuccessStatusCode)
            {
                Console.WriteLine("There was an error creating the MQ user account.");
                Thread.Sleep(2500);
                return false;
            }

            uri = $"http://YourServer:AndPort/api/permissions/%2F/{userName}";

            MqPermissions mqPermissions = new MqPermissions
            {
                configure = ".*",
                write = ".*",
                read = ".*"
            };

            info = JsonConvert.SerializeObject(mqPermissions);
            content = new StringContent(info, Encoding.UTF8, "application/json");

            httpResponseMessage = await httpClient.PutAsync(uri, content);

            if (!httpResponseMessage.IsSuccessStatusCode)
            {
                Console.WriteLine("There was an error creating the permissions on the MQ user account.");
                Thread.Sleep(2500);
                return false;
            }

            break;
    }
}
catch (Exception e)
{
    Console.WriteLine(e);
    throw;
}

我创建了简单的 MqUser 和 MqPermissions 类,所以我可以只使用 JsonConvert.SerializeObject 来传递信息。 另一个奇怪的事情是我公司选择将 MQ 虚拟主机命名为“/”。 到目前为止,这还不是问题,因为我们之前从未尝试过使用 API。 由于 / 字符应该在 uri 中,这是一个挂断,但我尝试将其编码为 %2F 并且它工作得很好。

【讨论】:

    猜你喜欢
    • 2020-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-29
    • 2017-01-03
    • 1970-01-01
    • 1970-01-01
    • 2013-10-28
    相关资源
    最近更新 更多