如何使用API​​控制器在.Net Core 2. *中设置自定义Webhook发送方和接收方实现

时间:2019-05-21 14:47:38

标签: c# asp.net-core asp.net-webhooks

我不知道如何在.Net Core 2 *中使用自定义发件人,自定义处理程序和持久性子发布存储来创建WebHook。

我已经阅读了许多解释Webhook的文章和示例,但是所有这些文章都使用.NetFramework而不是新的.Net Core。

我发现这些文章非常有益:

这是我当前用于WebHook发送器的一些代码:

Startup.cs

public void Configure(IApplicationBuilder app, HttpConfiguration config, IHostingEnvironment env)
{
config.InitializeCustomWebHooks();
config.InitializeCustomWebHooksApis();
}

NotifyApiController.cs(WebHooks发件人)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Http;
using Aeron.WebApi.Models.WebHookDtos;
using Aeron.WebApi.WebHookProviders;
using HttpPostAttribute = Microsoft.AspNetCore.Mvc.HttpPostAttribute;

[Authorize]
public class NotifyApiController : ApiController
{
    private static readonly List<MessageDto> Messages = new List<MessageDto>();

    public List<MessageDto> Get()
    {
        return Messages;
    }

    public async Task Post(MessageDto message)
    {
        Messages.Add(message);

        await this.NotifyAsync(WebHookFilterProvider.MessagePostedEvent, new { Message = message });
        Console.WriteLine($"MessagePostedEvent Notification send for message from {message.Sender}");
    }

    public async Task Delete(long id)
    {
        var messageToDelete = Messages.FirstOrDefault(m => m.Id == id);

        Messages?.Remove(messageToDelete);

        await this.NotifyAsync(WebHookFilterProvider.MessageRemovedEvent, new { Id = id });
        Console.WriteLine($"MessageRemovedEvent Notification send for message with Id {id}");
    }
}

WebHookFilterProvider.cs

using Microsoft.AspNet.WebHooks;
using System.Collections.ObjectModel;
using System.Threading.Tasks;

namespace Aeron.WebApi.WebHookProviders
{
    /// <summary>
    /// Use an <see cref="IWebHookFilterProvider"/> implementation to describe the events that users can 
    /// subscribe to. A wildcard filter is always registered meaning that users can register for 
    /// "all events". It is possible to have 0, 1, or more <see cref="IWebHookFilterProvider"/> 
    /// implementations.
    /// </summary>
    public class WebHookFilterProvider : IWebHookFilterProvider
    {
        public const string MessagePostedEvent = "MessagePostedEvent";
        public const string MessageRemovedEvent = "MessageRemovedEvent";

        private readonly Collection<WebHookFilter> filters = new Collection<WebHookFilter>
        {
            new WebHookFilter { Name = MessagePostedEvent, Description = "A message is posted."},
            new WebHookFilter { Name = MessageRemovedEvent, Description = "A message is removed."}
        };

        public Task<Collection<WebHookFilter>> GetFiltersAsync()
        {
            return Task.FromResult(filters);
        }
    }
}

我实际上不知道从这里做什么。

0 个答案:

没有答案