我如何实现一个webhook C#作为接收器后端和.net核心作为发布者?

svgewumm  于 2023-10-21  发布在  .NET
关注(0)|答案(1)|浏览(234)

我有这个要求使用webhook。
我对这个概念很陌生。
我正在努力实现这一点。
https://learn.microsoft.com/en-us/aspnet/webhooks/receiving/receivers
目前我有:

using JahezWebhookAPI.Models;
using Microsoft.AspNet.WebHooks;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Text.Json;
using System.Threading.Tasks;

namespace JahezWebhookAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class JahezSalesOrderHandler : ControllerBase,  IWebHookHandler
    { 
        public int Order => 1;

        public string Receiver => "JAHEZ";

        public List<JahezSalesOrder> SalesOrders { get; set; }

        [Route("Create")]
        [HttpPost]       
        public Task ExecuteAsync(string receiver, WebHookHandlerContext context)
        {

            CustomNotifications notifications = context.GetDataOrDefault<CustomNotifications>();
            foreach (var notification in notifications.Notifications)
            {
                foreach(var note in notification)
                {
                  //my logic goes here
                }
            }
            return Task.FromResult(true);
            
        }
    }
}

我有两个问题
第一个,我的客户端如何通过WebHookHandlerContext
第二,如何从任务结果返回OK?

xriantvc

xriantvc1#

这里是chatgpt答案?
使用Web API

rosoft.AspNetCore.Mvc;
using System.IO;
using System.Threading.Tasks;

namespace WebhookReceiver.Controllers
{
    [Route("api/webhook")]
    [ApiController]
    public class WebhookController : ControllerBase
    {
        [HttpPost]
        public async Task<IActionResult> ReceiveWebhook()
        {
            // Process the incoming webhook data here
            using (var reader = new StreamReader(Request.Body))
            {
                var body = await reader.ReadToEndAsync();
                // Process 'body' which contains the webhook data
            }

            return Ok(); // Respond with a 200 OK status
        }
    }
}

和消费者

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        using (var httpClient = new HttpClient())
        {
            var webhookUrl = "https://your-webhook-receiver-url/api/webhook"; // Replace with your receiver's URL
            var webhookData = "Your webhook data here"; // Replace with the actual data you want to send

            var response = await httpClient.PostAsync(webhookUrl, new StringContent(webhookData));
            
            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine("Webhook sent successfully.");
            }
            else
            {
                Console.WriteLine("Failed to send webhook: " + response.StatusCode);
            }
        }
    }
}

相关问题