ASP.NET WebHookReceiver "return HttpStatusCode.Unauthorized" returns HTML 代替

ASP.NET WebHookReceiver "return HttpStatusCode.Unauthorized" returns HTML instead

我正在为外部工具开发 webhook 接收器。

我正在使用 ASP.NET WebHooks 框架(更多:https://docs.microsoft.com/en-us/aspnet/webhooks/

一切都很好,除了一件事:我不能 return HttpStatusCode.Unauthorized。

这是 WebHookReceiver 中的代码结构:

public override async Task<HttpResponseMessage> ReceiveAsync(string id, HttpRequestContext context, HttpRequestMessage request)
        {
            try
            {
                var authheader = request.Headers.Authorization;
                if (authheader == null || string.IsNullOrEmpty(authheader.Parameter))
                {
                    return new HttpResponseMessage(HttpStatusCode.Unauthorized);
                }

我期待一个简单的 HTTP 响应,代码为 HttpStatusCode.Unauthorized(旁注,任何其他 Http 代码都按预期工作)。相反,它 return 是整个 HTML Microsoft 登录页面。我什至不知道它是从哪里来的。

我现在的解决方案只是 returning“BadRequest”和消息“Authorization failed”

好的,知道了。

这很正常。

https://www.restapitutorial.com/httpstatuscodes.html

The request requires user authentication. The response MUST include a WWW-Authenticate header field (section 14.47) containing a challenge applicable to the requested resource.

对于我的情况,我应该使用 403 Forbidden