Webhook 是一个 API 概念,是微服务 API 的使用范式之一,也被称为反向 API,即前端不主动发送请求,完全由后端推送;
常见于 微信或支付宝的支付回调,简道云的数据推送等。
基于web API (v2.1)
实现方式 :
[HttpPost]
[Route("api/callback")] public async Task<dynamic> CallBackByJdy() { Dictionary<string, string> dic = new Dictionary<string, string>(); try { var stream = new MemoryStream(); await Request.Content.CopyToAsync(stream); stream.Seek(0, SeekOrigin.Begin); var body = await new StreamReader(stream).ReadToEndAsync();//获取回调的请求体 body;
//可对body进行处理 业务逻辑code
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK); foreach (var value in response.RequestMessage.Headers) { dic.Add(value.Key, value.Value.First()); //获取请求头存入dic字典中 }
var uri = response.RequestMessage.RequestUri;//获取请求地址 var nonce = HttpUtility.ParseQueryString(uri.Query).Get("nonce");//请求地址中包含的参数 var timestamp = HttpUtility.ParseQueryString(uri.Query).Get("timestamp"); var signature = dic.FirstOrDefault(t=>t.Key=="X-JDY-Signature").Value;//读取字典中的请求头数据 return ResponseMessage(response);//返回响应 } catch (Exception ex) { HttpResponseMessage message = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "fail", ex); return ResponseMessage(message); //throw; } }