You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# WebHook接收端开发疑问:WebHookHandlerContext传递与Task返回OK

ASP.NET WebHook接收端常见问题解答

问题1:客户端如何传递WebHookHandlerContext?

WebHookHandlerContext不是由客户端直接传递的,它是ASP.NET WebHook框架在处理客户端请求时自动创建并注入到ExecuteAsync方法中的。

客户端只需要按以下要求发送请求即可:

  • 发送POST请求到WebHook接收端的约定路由(通常是api/webhooks/incoming/JAHEZ,对应你定义的Receiver = "JAHEZ")
  • 请求体携带符合格式的业务数据(比如JSON格式的通知内容)
  • 如果配置了签名验证,请求头需带上对应的签名信息

框架会自动完成请求体解析、签名验证(若开启),并将请求数据封装到WebHookHandlerContext的Data属性中,你只需通过context.GetDataOrDefault<T>()方法就能获取客户端传递的业务数据。

问题2:如何在Task执行结果中返回OK状态?

情况1:使用IWebHookHandler默认行为

如果你通过实现IWebHookHandler处理WebHook,框架默认会在ExecuteAsync方法执行完成且未抛出异常时,自动向客户端返回200 OK响应,无需手动返回结果。你当前代码中return Task.FromResult(true);的写法可以简化为return Task.CompletedTask;,效果一致。

情况2:自定义响应内容或状态码

如果需要返回自定义响应内容或状态码,可通过设置WebHookHandlerContext.Response属性实现:

public Task ExecuteAsync(string receiver, WebHookHandlerContext context)
{
    // 业务逻辑处理
    CustomNotifications notifications = context.GetDataOrDefault<CustomNotifications>();
    foreach (var notification in notifications.Notifications)
    {
        foreach(var note in notification)
        {
            // 你的业务逻辑
        }
    }

    // 自定义OK响应
    context.Response = new HttpResponseMessage(System.Net.HttpStatusCode.OK)
    {
        Content = new StringContent("WebHook处理成功")
    };

    return Task.CompletedTask;
}

代码写法修正提示

你当前的代码存在误区:实现IWebHookHandler的类不需要继承ControllerBase,也不需要给ExecuteAsync添加[HttpPost]、[Route]等属性。这些属性用于定义普通API接口,而IWebHookHandler是由WebHook框架自动发现并调用的,正确写法示例:

using JahezWebhookAPI.Models;
using Microsoft.AspNet.WebHooks;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace JahezWebhookAPI.WebHooks
{
    public class JahezSalesOrderHandler : IWebHookHandler
    { 
        public int Order => 1;

        public string Receiver => "JAHEZ";

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

        public Task ExecuteAsync(string receiver, WebHookHandlerContext context)
        {
            CustomNotifications notifications = context.GetDataOrDefault<CustomNotifications>();
            foreach (var notification in notifications.Notifications)
            {
                foreach(var note in notification)
                {
                    // 你的业务逻辑
                }
            }

            return Task.CompletedTask;
        }
    }
}

内容的提问来源于stack exchange,提问作者user123456

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 10:16:19