c# - 将 JSON 数据路由到 Azure 中的事件中心
问题描述
我有一种情况,我需要通过事件中心将 JSON 数据(一个 JSON 文件,而不是转换为 JSON)发送到时序见解。但由于缺乏 C# 经验,我无法发送数据。
我可以发送其他示例消息,但不能发送 JSON。我怎样才能做到这一点?
任何帮助或见解将不胜感激。
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
using System.IO;
using Microsoft.ServiceBus.Messaging;
namespace ConsoleApp5
{
class Program
{
static string _connectionString = "Endpoint..;
static async Task MainAsync(string[] args)
{
var client = EventHubClient.CreateFromConnectionString(_connectionString, "eventhub");
var json = File.ReadAllText(@"C:\Users\Shyam\Downloads\personal.json");
var eventData = new EventData(Encoding.UTF8.GetBytes(json));
await EventHubClient.SendAsync(eventData);
}
}
}
但是,它会在异步方法中引发错误。
严重性代码 描述 项目文件行抑制状态错误 CS0120 非静态字段、方法或属性需要对象引用 'EventHubClient.SendAsync(EventData)' ConsoleApp5 C:\Users\Shyam\source\repos\ConsoleApp5\ConsoleApp5\ Program.cs 21 活动
更新:
namespace jsonData
{
using System;
using System.Text;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Azure.EventHubs;
public class Program
{
private static EventHubClient eventHubClient;
private const string EhConnectionString = "Endpoint=sb://";
private const string EhEntityPath = "hub";
public static void Main(string[] args)
{
MainAsync(args).GetAwaiter().GetResult();
}
private static async Task MainAsync(string[] args)
{
// Creates an EventHubsConnectionStringBuilder object from the connection string, and sets the EntityPath.
// Typically, the connection string should have the entity path in it, but this simple scenario
// uses the connection string from the namespace.
var connectionStringBuilder = new EventHubsConnectionStringBuilder(EhConnectionString)
{
EntityPath = EhEntityPath
};
eventHubClient = EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString());
var json = File.ReadAllText(@"D:\Sample.json");
var eventData = new EventData(Encoding.UTF8.GetBytes(json));
await eventHubClient.SendAsync(eventData);
await eventHubClient.CloseAsync();
Console.WriteLine("Press ENTER to exit.");
Console.ReadLine();
}
}
}
解决方案
我相信你现在已经弄清楚了,但你的问题不在于 JSON,而在于你如何使用事件中心客户端。
而不是这一行:
await EventHubClient.SendAsync(eventData);
应该是这样的:
await client.SendAsync(eventData);
推荐阅读
- php - Laravel with() 仅适用于第一条记录(仅适用于 id 为 1 的记录)
- opencv - 您如何计算图像左上角四分之一的相机外在因素?
- c# - 异步方法将响应发送回 Main
- python - 如何用 OpenCV 夸大颜色差异?
- powershell - 将 ConvertFrom-String 与所有数据集中不存在的值一起使用
- python - Django 首次运行:SyntaxError: invalid syntax
- matlab - 如何将圆的估计半径转换为其实际范围?
- vba - 使用模块代码导入时访问错误3043(网络访问中断)
- c++ - 了解 C++ 代码 - “获取 int 中的位数”
- ruby-on-rails - 找不到身份证