【问题标题】:Working with Azure Event Grid and blob storage使用 Azure 事件网格和 Blob 存储
【发布时间】:2018-04-19 03:19:43
【问题描述】:

我是 Azure 事件网格和 Webhook 的新手。

如何将我的 .net mvc web api 应用程序绑定到 Microsoft Azure 事件网格?

简而言之,我希望,每当将新文件添加到 blob 存储时,Azure 事件网格都应该通知我的 Web api 应用程序。

我尝试了以下文章,但没有运气 https://docs.microsoft.com/en-us/azure/storage/blobs/storage-blob-event-quickstart

【问题讨论】:

    标签: c# azure webhooks azure-eventgrid


    【解决方案1】:

    您还可以使用 Microsoft.Azure.EventGrid nuget 包。

    来自以下文章(感谢 gldraphael):https://gldraphael.com/blog/creating-an-azure-eventgrid-webhook-in-asp-net-core/

    [Route("/api/webhooks"), AllowAnonymous]
    public class WebhooksController : Controller
    {
        // POST: /api/webhooks/handle_ams_jobchanged
        [HttpPost("handle_ams_jobchanged")] // <-- Must be an HTTP POST action
        public IActionResult ProcessAMSEvent(
            [FromBody]EventGridEvent[] ev, // 1. Bind the request
            [FromServices]ILogger<WebhooksController> logger)
        {
            var amsEvent = ev.FirstOrDefault(); // TODO: handle all of them!
            if(amsEvent == null) return BadRequest();
    
            // 2. Check the eventType field
            if (amsEvent.EventType == EventTypes.MediaJobStateChangeEvent)
            {
                // 3. Cast the data to the expected type
                var data = (amsEvent.Data as JObject).ToObject<MediaJobStateChangeEventData>();
    
                // TODO: do your thing; eg:
                logger.LogInformation(JsonConvert.SerializeObject(data, Formatting.Indented));
            }
    
            // 4. Respond with a SubscriptionValidationResponse to complete the 
            // event subscription handshake.
            if(amsEvent.EventType == EventTypes.EventGridSubscriptionValidationEvent)
            {
                var data = (amsEvent.Data as JObject).ToObject<SubscriptionValidationEventData>();
                var response = new SubscriptionValidationResponse(data.ValidationCode);
                return Ok(response);
            }
            return BadRequest();
        }
    }
    
    

    【讨论】:

      【解决方案2】:

      以下是如何使用 Web API 处理它的最新示例。您还可以从此处查看和部署工作示例:https://github.com/dbarkol/azure-event-grid-viewer

          [HttpPost]
          public async Task<IActionResult> Post()
          {
              using (var reader = new StreamReader(Request.Body, Encoding.UTF8))
              {
                  var jsonContent = await reader.ReadToEndAsync();
      
                  // Check the event type.
                  // Return the validation code if it's 
                  // a subscription validation request. 
                  if (EventTypeSubcriptionValidation)
                  {
                      var gridEvent =
                          JsonConvert.DeserializeObject<List<GridEvent<Dictionary<string, string>>>>(jsonContent)
                              .First();
      
      
                      // Retrieve the validation code and echo back.
                      var validationCode = gridEvent.Data["validationCode"];
                      return new JsonResult(new{ 
                          validationResponse = validationCode
                      });
                  }
                  else if (EventTypeNotification)
                  {
                      // Do more here...
                      return Ok();                 
                  }
                  else
                  {
                      return BadRequest();
                  }
              }
      
          }
      
      public class GridEvent<T> where T: class
      {
          public string Id { get; set;}
          public string EventType { get; set;}
          public string Subject {get; set;}
          public DateTime EventTime { get; set; } 
          public T Data { get; set; } 
          public string Topic { get; set; }
      }
      

      【讨论】:

        【解决方案3】:

        您可以通过创建将订阅从事件网格发布的事件的自定义端点来完成此操作。您引用的文档使用 Request Bin 作为订阅者。而是在您的 MVC 应用程序中创建一个 Web API 端点来接收通知。您必须支持验证请求才能使您拥有有效的订阅者,然后您就可以关闭并运行。

        例子:

            public async Task<HttpResponseMessage> Post()
            {
                if (HttpContext.Request.Headers["aeg-event-type"].FirstOrDefault() == "SubscriptionValidation")
                {
                    using (var reader = new StreamReader(Request.Body, Encoding.UTF8))
                    {
                        var result = await reader.ReadToEndAsync();
                        var validationRequest = JsonConvert.DeserializeObject<GridEvent[]>(result);
                        var validationCode = validationRequest[0].Data["validationCode"];
        
                        var validationResponse = JsonConvert.SerializeObject(new {validationResponse = validationCode});
                        return new HttpResponseMessage
                        {
                            StatusCode = HttpStatusCode.OK, 
                            Content = new StringContent(validationResponse)
                        };                       
                    }
                }
        
                // Handle normal blob event here
        
                return new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
            }
        

        【讨论】:

        • 您好,我们如何在 WEB API 中检查并发送此验证码?
        【解决方案4】:

        如何将我的 .net mvc web api 应用程序绑定到 Microsoft Azure 事件网格? 简而言之,我希望,每当将新文件添加到 blob 存储时,Azure 事件网格都应该通知我的 web api 应用程序。

        我为此做了一个演示,它在我这边可以正常工作。您可以参考以下步骤:

        1.创建一个带函数的演示RestAPI项目

         public string Post([FromBody] object value) //Post
         {
              return $"value:{value}";
         }
        

        2.如果我们想将 Azure Storage 与 Azure Event Grid 集成,我们需要在 West US2West Central US 位置创建一个blob storage account。更多细节可以参考截图。

        2.创建Storage Accounts类型事件订阅并绑定自定义API端点

        3.将 blob 上传到 blob 存储并从 Rest API 进行检查。

        【讨论】:

        • 太棒了。有效。我试图将它部署在美国东部的位置,这是错误的。谢谢你:)
        • 我用 RequestBin 工具测试了整个东西,它按预期工作。但是现在当我尝试使用我的 web api url 更改完整端点 URL 时,azure 不接受/保存更改。我需要 https web api URL 吗?现在我有 http url
        • @Tom Sun,您是否使用示例 WEB API 检查了相同的示例?
        猜你喜欢
        • 2021-03-08
        • 1970-01-01
        • 2017-03-26
        • 2020-12-12
        • 2021-02-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-02
        相关资源
        最近更新 更多