问题描述
我已经使用.net核心应用程序创建了API,该应用程序用于将一组属性发送到SQL DB,并且消息的一个副本也应该发送到azure服务总线主题.截至目前,.net core不支持服务总线.请分享您的想法.如何使用.net核心应用程序将消息发送到服务总线主题?
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. As of now .net core doesn't support service bus. Kindly share your thoughts. How can I send the messages to the service bus topic using .net core application?
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);
}
推荐答案
使用.Net Core发送消息非常容易.有一个专用的nuget软件包: Microsoft.Azure.ServiceBus .
It is very easy to send messages with .Net Core. There is a dedicated nuget package for it: 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/
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/2018/02/28/receiving-messages-azure-service-bus-net-core/
And another one about receiving messages: http://www.michalbialecki.com/2018/02/28/receiving-messages-azure-service-bus-net-core/
这篇关于如何从.net核心应用程序向服务总线主题发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!