为什么我的 Application_BeginRequest in Global.asax.cs 没有被自托管 WCF 服务调用

Why is my Application_BeginRequest in Global.asax.cs not getting called with a self hosted WCF service

我正在自行托管需要支持入站 CORS REST 流量的 WCF 服务。所以我用下面的代码块添加了 Global.asax.cs 文件,但是 Application_BeginRequest() 永远不会触发。我也在我的 app.Config 中设置了。还有什么我需要做的吗?这适用于自托管服务还是仅适用于通过 IIS 托管的服务?

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        string origin = HttpContext.Current.Request.Headers["origin"];
        if (!String.IsNullOrEmpty(origin)) // CORS origin?
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", origin);

        if (HttpContext.Current.Request.HttpMethod == "OPTIONS") // CORS origin w/ options?
        {
            var requestedHeaders = HttpContext.Current.Request.Headers["Access-Control-Request-Headers"];
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", requestedHeaders);
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET,POST,PUT,OPTIONS,DELETE");
            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
            HttpContext.Current.Response.StatusCode = 200;
            HttpContext.Current.Response.End();
        }
    }

只有托管在 IIS 上的全局文件才会生效。 IIS 会将 WCF 服务视为 Web 服务来解析其全局文件。如果是self-hosted,则不解析全局文件,运行.

我们可以让WCF支持JSONP来解决cross-domain:

<binding name="bind1" crossDomainScriptAccessEnabled="true">
</binding>

您还可以实现 IDispatchMessageInspector 以在服务 responds.This 解决方案适用于 self-hosting 之前添加响应 headers。

public class ServerMessageLogger : IDispatchMessageInspector
    {
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
           return null;
        }

        public void BeforeSendReply(ref Message reply, object correlationState)
        {
            WebOperationContext ctx = WebOperationContext.Current;
            ctx.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*");
        }
    }

更多关于IDispatchMessageInspector的内容,请参考以下内容link:

https://docs.microsoft.com/en-us/dotnet/api/system.servicemodel.dispatcher.idispatchmessageinspector?view=netframework-4.8

如果还有不明白的可以参考下面的link,里面有完整的代码:

How to enable Cross-Origin Resource Sharing in .Net Console Application WCF Service?

更新

以下图片是我的演示:

上面两张图一张用了WebOperationContext一张没用

其实WebOperationContext和HttpContext类似。 WebOperationContext 通常用在 WCF REST 方法中,而 HttpContext 通常用在 ASP.NET WebForms 页面或 ASMX Web Service Web 方法中。