Asp.net WebForms WebHook接收器:如何读取multipart/form-data格式的请求体数据
解决ASP.NET WebForms中读取multipart/form-data格式WebHook请求体的问题
看起来你碰到的问题是WebHook发送的请求并非预期的JSON格式,而是multipart/form-data——这也是不少支付类或第三方服务WebHook常用的传输格式。不用手动去解析那串带分隔符的内容,ASP.NET已经帮我们封装好了便捷的读取方式,直接用内置的API就能搞定。
修改后的WebHook处理代码
直接通过HttpContext.Request.Form集合就能获取到所有表单字段的键值对,完全不需要手动读取输入流或者强行解析JSON:
using System; using System.Web; namespace Web_Site { /// <summary> /// Summary description for WebHook /// </summary> public class WebHook : IHttpHandler { public void ProcessRequest(HttpContext context) { try { // 从Request.Form中直接提取multipart/form-data的各个字段 string id = context.Request.Form["id"]; string txid = context.Request.Form["txid"]; string explorerUrl = context.Request.Form["explorer_url"]; string merchantId = context.Request.Form["merchant_id"]; string type = context.Request.Form["type"]; string coinShortName = context.Request.Form["coin_short_name"]; string walletId = context.Request.Form["wallet_id"]; string walletName = context.Request.Form["wallet_name"]; string address = context.Request.Form["address"]; string amount = context.Request.Form["amount"]; string confirmations = context.Request.Form["confirmations"]; string date = context.Request.Form["date"]; // 这里可以添加你的业务逻辑,比如把数据存入数据库、记录操作日志等 // 调试示例:将关键信息输出到VS的输出窗口 System.Diagnostics.Debug.WriteLine($"收到交易ID: {txid}, 金额: {amount}"); // 返回200状态码告知发送方已成功接收请求 context.Response.StatusCode = 200; context.Response.Write("WebHook已成功接收"); context.Response.Flush(); context.Response.SuppressContent = true; context.ApplicationInstance.CompleteRequest(); } catch (Exception ex) { // 异常处理:返回500错误并记录异常信息 context.Response.StatusCode = 500; context.Response.Write($"处理WebHook时出错: {ex.Message}"); System.Diagnostics.Debug.WriteLine($"WebHook异常详情: {ex.ToString()}"); } } public bool IsReusable { get { return true; } } } }
关键说明
- 原代码报错的核心原因:你试图把
multipart/form-data格式的文本当作JSON解析,格式不匹配自然会抛出解析错误。 Request.Form是ASP.NET自动解析的集合,不管请求是application/x-www-form-urlencoded还是multipart/form-data格式,都能正确读取所有键值对,无需手动处理分隔符和内容头。- 建议在业务逻辑中添加完善的日志记录,方便后续排查问题;同时务必返回200状态码,避免WebHook发送方因为未收到成功响应而重复推送请求。
内容的提问来源于stack exchange,提问作者SilverLight
相关产品推荐
相关产品推荐

