通过浏览器访问此 URL 时,下面的代码会抛出 404 https://www.example.com/api/my_webhook/,我不明白为什么。当我通过 .NET 代码 POST 到该 URL 时,Webhook 可以正常工作。这似乎与某种不正确的重写有关。我希望浏览器返回诸如无效请求之类的内容(因为它应该是 POST 请求)。
myservice.svc.vb
Public Async Sub myWebhook(ByVal stream As Stream) Implements Imyservice.myWebhook
End Sub
Imyservice.vb
<ServiceContract()>
Public Interface Imyservice
<OperationContract()>
<Web.WebInvoke(Method:="POST", ResponseFormat:=Web.WebMessageFormat.Json, BodyStyle:=Web.WebMessageBodyStyle.Bare,
UriTemplate:="my_webhook")>
Sub myWebhook(ByVal stream As Stream)
End Interface
web.config
以下规则是我的
<rules>
部分中的第一条规则:
<rule name="RemoveSvcExtension" stopProcessing="true">
<match url="^(.*)api/(.*)$"/>
<action type="Rewrite" url="{R:1}myservice.svc/{R:2}" logRewrittenUrl="true"/>
</rule>
Global.asax.vb
Sub Application_EndRequest(ByVal sender As Object, ByVal e As EventArgs)
If Context.Response.StatusCode = 404 Then
'this code block is hit
End If
End Sub
我认为您遇到的问题是由于当您尝试通过浏览器(使用 GET 请求)访问 URL 时,URL 重写重写了 URL,这与需要 POST 请求的操作定义不匹配。
要使 URL 重写正常工作,您可以考虑以下步骤:
确保重写规则仅适用于 POST 请求:您可以通过向规则添加条件以使其仅匹配 POST 请求来实现此目的。
<rule name="RemoveSvcExtension" stopProcessing="true">
<match url="^(.*)api/(.*)$"/>
<conditions>
<add input="{REQUEST_METHOD}" pattern="^POST$" />
</conditions>
<action type="Rewrite" url="{R:1}myservice.svc/{R:2}" logRewrittenUrl="true"/>
考虑处理端点的 GET 请求:如果您希望用户或开发人员通过浏览器访问端点以进行测试或其他目的,您可以添加一个服务方法来处理 GET 请求并返回更具描述性的消息。
我希望这有帮助。