问题描述
我使用 Azure.Messaging.EventGrid 版本 4.0.0-beta.4 将事件发布到事件网格主题。
我认为我已经正确设置了客户端并且正在调用正确的方法来发布事件,但是我遇到了这个异常:
Azure.RequestFailedException: 'Service request failed.
Status: 400 (Unexpected property 'source' found in JSON. Expected:
StartObject,actual: StartArray)
这是我根据给定的示例 here 编写的代码:
Uri endpoint = new Uri("myEndpoint");
string accessKey = "myAccessKey";
string topicName = "MyTopic1";
EventGridPublisherClient client = new EventGridPublisherClient(
endpoint,new AzureKeyCredential(accessKey));
MyCustomObj obj = new MyCustomObj() {
Description = "Test description",Name = "Test name",Id = 1234};
List<EventGridEvent> eventsList = new List<EventGridEvent>
{
new EventGridEvent(
obj,"myCustomObject","myEventType","v1"
)
};
await client.SendEventsAsync(eventsList);
解决方法
我想出了问题。原来我应该发布 CloudEvent
而不是 EventGridEvent
。在 Azure 门户上花费大量时间后,我发现我尝试发布的主题仅接受 CloudEvent
。找到此信息需要进行大量探索,因为它非常隐蔽。但我是这样找到的:
当您在“概览”选项卡上时,在您可以找到“主题端点”的正上方有一个“Json 视图”链接:
点击它并选择最新的 API 版本。这里告诉我 inputSchema
是 CloudEventSchemaV1_0
:
更改事件类型后,我能够发布事件:
List<CloudEvent> eventsList = new List<CloudEvent>
{
new CloudEvent(
"localhost","myEventType",obj
)
};
await client.SendEventsAsync(eventsList);
这本不应该引起这么多麻烦...
无论如何...我仍然困惑的一个方面是为什么CloudEvent
的属性与EventGridEvent
的属性不同?还有一个有数据版本属性,但另一个没有。我该如何选择使用哪个?