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

时间:2017-04-30 07:55:06

标签: c# azure asp.net-core-webapi azure-servicebus-topics

我使用.net核心应用程序创建了API,该应用程序用于将一组属性发送到SQL DB,并且还应将一个消息副本发送到azure服务总线主题。截至目前.net核心不支持服务总线。请分享您的想法。如何使用.net核心应用程序将消息发送到服务总线主题?

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);
    }

3 个答案:

答案 0 :(得分:2)

有一个由Microsoft编写的.NET Standard客户端。尝试一下。

请参阅此内容 - https://blogs.msdn.microsoft.com/servicebus/2016/12/20/service-bus-net-standard-and-open-source/

和 - https://github.com/azure/azure-service-bus-dotnet

答案 1 :(得分:2)

使用.Net Core发送邮件非常容易。有一个专门的nuget包: Microsoft.Azure.ServiceBus

示例代码如下所示:

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);
        }
    }
}

有关完整示例,您可以查看我的博文:http://www.michalbialecki.com/2017/12/21/sending-a-azure-service-bus-message-in-asp-net-core/

另一个关于接收消息:http://www.michalbialecki.com/2018/02/28/receiving-messages-azure-service-bus-net-core/

答案 2 :(得分:1)

以下是使用.Net Core向Azure Service Bus主题发送消息的方法:

别忘了将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);
            }
        }
    }
}

希望这会有所帮助!