如何在IIS托管的网站中收到自定义的Webhook? [英] How do I receive a custom webhook in an IIS hosted website?

查看:169
本文介绍了如何在IIS托管的网站中收到自定义的Webhook?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我所做的:

1-我已经安装了nuget软件包:Microsoft.AspNet.WebHooks.Receivers.Custom 1.2.0-beta

1 - I have installed the nuget package: Microsoft.AspNet.WebHooks.Receivers.Custom 1.2.0-beta

2-我将 WebApiConfig 配置为接收自定义的webhooks:

2 - I configured the WebApiConfig to receive custom webhooks:

    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        config.InitializeReceiveCustomWebHooks(); //<<<---
    }

3-我在web.config中设置了一个秘密密钥:

3 - I set up a secret key in the web.config:

  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    ...
    <add key="MS_WebHookReceiverSecret_GenericJson" value="z=SECRET"/> 
  </appSettings>

4-我编写了一个基本的接收器(带有genericjson钩子捕获)

4 - I have written a basic receiver (with the genericjson hook capture)

public class GenericJsonWebHookHandler : WebHookHandler
{
    public static string dataReceived;
    public GenericJsonWebHookHandler()
    {
        this.Receiver = "genericjson";
    }

    public override Task ExecuteAsync(string generator, WebHookHandlerContext context)
    {
        // Get JSON from WebHook
        JObject data = context.GetDataOrDefault<JObject>();

        if (context.Id == "i")
        {
            // do stuff
        }
        else if (context.Id == "z")
        {
            // do more stuff
            dataReceived = data.ToString();

            File.Create(@"c:\test\test1.txt");
        }

        return Task.FromResult(true);
    }
}

现在,可以期望通过上述步骤进行操作,如果设置了Webhook发件人以将Json发布到IIS托管站点,它应该将通知捕获为Json,将捕获的数据分配给 dataReceived 并将空白文本文件写入 c:\ test \ test.txt -情况并非如此

Now, one would expect with the steps above, if a webhook sender is set up to publish Json to the IIS hosted site, it should capture the notification as Json, assign the captured data to dataReceived and write a blank text file to c:\test\test.txt - which was not the case

当前,我正在使用Team Foundation Server进行测试,以将Webhook测试发送到 https://mywebbhooksite.com:5050/?z=SECRET ,并且成功>-但是,当我检查是否已经创建了那个小的测试文件时,它不存在.我还在主页上运行了一些JavaScript,以轮询 dataReceived 的任何更改,但我什么都没看到.

Currently, I am testing this using Team Foundation Server to send a webhook test to https://mywebbhooksite.com:5050/?z=SECRET, and It succeeds - however, when I check if that little test file has been created, it's not there. I also have some javascript running on the homepage to poll for any changes to dataReceived but I see nothing is happening.

此处提到:我在w3wp.exe进程上附加了一个远程调试器,ExecuteAsync和GenericJsonWebHookHandler上的断点没有被击中

是否还需要进行其他特定设置才能捕获Webhook?

Are there any other specific setup that needs to be done in order for the webhook to be captured?

推荐答案

我采取了一种可行的肮脏方法

I took a filthy approach which works

我放弃了 GenericJsonWebHookHandler ,而是使用了 WebApiApplication 中的 Application_BeginRequest()事件,而不是拦截了发件人Webhook发布的数据.挂钩的主体位于 HttpRequest.Request.Inputstream 中,可以使用流读取器将其打开.内容可以读取到 string 上并解析为JObject(如果webhook请求发送的请求的主体为JSon)

I ditched GenericJsonWebHookHandler and instead I have utilized the Application_BeginRequest() event in WebApiApplication instead to intercept data posted by the sender Webhook. The body of the hook resides in the HttpRequest.Request.Inputstream, which can be opened using a streamreader. The contents can be read onto a string and parsed into a JObject (if the body of the request sent by the webhook Request is JSon)

这是我的代码.

    protected void Application_BeginRequest()
    {
        if (!Request.HttpMethod.Equals("post", StringComparison.InvariantCultureIgnoreCase)) {
            return; 
        }

        string documentContents;
        using (var receiveStream = Request.InputStream)
        {
            using (var readStream = new StreamReader(receiveStream, Encoding.UTF8))
            {
                documentContents = readStream.ReadToEnd();
            }
        }

        try
        {
            var json = JObject.Parse(documentContents);
            File.WriteAllLines(@"C:\test\keys.txt", new[] { documentContents, "\r\n", json.ToString() });
        }
        catch (Exception)
        {
             // do something
        }
    }

测试:

我进入了Webhook,开始了一个Webhook测试.它使用json发布了请求.HTTP 200是服务器的响应.

I went onto my webhook and commenced a webhook test. It published the request with the json. HTTP 200 was the response from the server.

断点被击中. HttpMethod 接了这篇文章.已读取请求的 InputStream ,并将其存储在 documentContents 中.触发 JObject.Parse 并将帖子内容放入名为 json

Breakpoint was hit. The HttpMethod picked up the post. The Request's InputStream was read and stored in documentContents. JObject.Parse fired off and put the contents of the post into a JObject variable called json

json 的内容已写入存储在服务器上的文件中-表示已正确接收到请求.

The contents of json was written to a file stored on the server - indicating that the request was properly received.

为了安全起见,我打算做些什么来改善这一点

出于安全目的,我将加密在web.config中设置的密钥,然后在web.config中设置加密的密钥,然后将其与传入的URL查询参数进行匹配(使用相同的加密算法))以查看该键是否存在并且完全相同

For security purposes, I will encrypt the secret key I set in the web.config, and set the encrypted key in the web.config instead, and after that match it with the incoming URL Query parameters (using the same encryption algorithm) to see if that key is present and exactly the same

这篇关于如何在IIS托管的网站中收到自定义的Webhook?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆