简体   繁体   English

如何从 .net 核心应用程序向服务总线主题发送消息

[英]How to send a message to service bus topic from .net core application

I've created API using .net core application, which is used to send set of properties to the SQL DB and also one copy of the message should be sent to the azure service bus topic.我已经使用 .net 核心应用程序创建了 API,该应用程序用于将一组属性发送到 SQL DB,并且还应将消息的一个副本发送到 azure 服务总线主题。 As of now .net core doesn't support service bus.截至目前,.net 核心不支持服务总线。 Kindly share your thoughts.请分享您的想法。 How can I send the messages to the service bus topic using .net core application?如何使用 .net core 应用程序将消息发送到服务总线主题?

public class CenterConfigurationsDetails
{

    public Guid Id { get; set; } = Guid.NewGuid();

    public Guid? CenterReferenceId { get; set; } = Guid.NewGuid();

    public int? NoOfClassRooms { get; set; }

    public int? OtherSpaces { get; set; }

    public int? NoOfStudentsPerEncounter { get; set; }

    public int? NoOfStudentsPerComplimentaryClass { get; set; }
}

    // POST api/centers/configurations
    [HttpPost]
    public IActionResult Post([FromBody]CenterConfigurationsDetails centerConfigurationsDetails)
    {
        if (centerConfigurationsDetails == null)
        {
            return BadRequest();
        }
        if (_centerConfigurationModelCustomValidator.IsValid(centerConfigurationsDetails, ModelState))
        {
            var result = _centerConfigurationService.CreateCenterConfiguration(centerConfigurationsDetails);

            return Created($"{Request.Scheme}://{Request.Host}{Request.Path}", result);
        }
        var messages = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage).ToList();
        return BadRequest(messages);
    }

It is very easy to send messages with .Net Core.使用 .Net Core 发送消息非常容易。 There is a dedicated nuget package for it: Microsoft.Azure.ServiceBus .有一个专用的 nuget 包: Microsoft.Azure.ServiceBus

Sample code can look like this:示例代码如下所示:

public class MessageSender
{
    private const string ServiceBusConnectionString = "Endpoint=sb://bialecki.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=[privateKey]";

    public async Task Send()
    {
        try
        {
            var productRating = new ProductRatingUpdateMessage { ProductId = 123, RatingSum = 23 };
            var message = new Message(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(productRating)));

            var topicClient = new TopicClient(ServiceBusConnectionString, "productRatingUpdates");
            await topicClient.SendAsync(message);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
    }
}

For full example you can have a look at my blog post: http://www.michalbialecki.com/2017/12/21/sending-a-azure-service-bus-message-in-asp-net-core/有关完整示例,您可以查看我的博客文章: http : //www.michalbialecki.com/2017/12/21/sending-a-azure-service-bus-message-in-asp-net-core/

And another one about receiving messages: http://www.michalbialecki.com/2018/02/28/receiving-messages-azure-service-bus-net-core/还有一个关于接收消息的: http : //www.michalbialecki.com/2018/02/28/receiving-messages-azure-service-bus-net-core/

Here's how to use .Net Core to send a message to the Azure Service Bus Topic:以下是如何使用 .Net Core 向 Azure 服务总线主题发送消息:

Don't forget to add the Microsoft.Azure.ServiceBus nuget package to your project.不要忘记将Microsoft.Azure.ServiceBus nuget 包添加到您的项目中。

using Microsoft.Azure.ServiceBus;
using Newtonsoft.Json;
using System;
using System.Text;
using System.Threading.Tasks;

namespace MyApplication
{
    class Program
    {
        private const string ServiceBusConnectionString = "Endpoint=[SERVICE-BUS-LOCATION-SEE-AZURE-PORTAL];SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=[privateKey]";

        static void Main(string[] args)
        {
            Task.Run(async () =>
            {
                await Send(123, "Send this message to the Service Bus.");
            });

            Console.Read();
        }

        public static async Task Send(int id, string messageToSend)
        {
            try
            {
                var messageObject = new { Id = id, Message = messageToSend };

                var message = new Message(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(messageObject)));

                var topicClient = new TopicClient(ServiceBusConnectionString, "name-of-your-topic");

                await topicClient.SendAsync(message);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

Hope this helps!希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 向服务总线主题发送消息 - send message to service bus topic 如何在 Azure 服务总线中显式向主题订阅死信队列发送消息 - How to send message to Topic Subscription Dead Letter Queue Explicitly in Azure Service Bus 如何将消息从Deadletter主题发送到Main并使用.net core C#完成消息 - How to send message from Deadletter topic to Main and complete it using .net core c# 从 Azure 服务总线主题读取的 Asp.net Core 2.2 - Asp.net Core 2.2 read from Azure Service Bus Topic 从 Azure function 向服务总线主题发送批处理消息 - Send batch messages to Service Bus topic from Azure function 如何在Azure Service Bus主题上删除DeadLetter消息 - How do I delete a DeadLetter message on an Azure Service Bus Topic 如何使用 Azure Functions 将数据发送到服务总线主题? - How to send data to Service Bus Topic with Azure Functions? 使用 Azure 中的 IAsyncCollector 将消息从服务总线主题批量发送到另一个主题即使在收到消息后功能也会保持重试 - Send Messages from service bus topic to another as batches using IAsyncCollector in Azure Functions keeps retries even after message received 跟踪服务总线消息主题订阅 - Track Service Bus Message Topic Subscription Azure Service Bus主题-订阅消息到期 - Azure Service Bus topic - subscription message expiry
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM