0

I'm self hosting a WCF service that needs to support inbound CORS REST traffic. So I added the Global.asax.cs file with the following code block, but the Application_BeginRequest() never fires. I also have set in my app.Config. Is there anything else I need to do and does this work for self hosted services or just services hosted via 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();
        }
    }

1 Answers1

2

Only Global files hosted on IIS will take effect. IIS will treat WCF service as a web service to parse its Global file. If it is self-hosted, Global file will not be parsed and run.

We can make WCF support JSONP to solve cross-domain:

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

You can also implement IDispatchMessageInspector to add response headers before the service responds.This solution is suitable for self-hosting.

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", "*");
        }
    }

For more information about IDispatchMessageInspector,Please refer to the following link:

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

If you are still unclear, you can refer to the link below, which contains the complete code:

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

UPDATE

The following pictures is my demo:

enter image description here

enter image description here

One of the two pictures above uses WebOperationContext one does not use.

In fact, WebOperationContext is similar to HttpContext. WebOperationContext is usually used in WCF REST methods, and HttpContext is usually used in ASP.NET WebForms pages or ASMX Web Service Web methods.

Ding Peng
  • 3,702
  • 1
  • 5
  • 8
  • Thanks for your help. Adding the crossDomainScriptAccessEnabled='true' fails in the binding and throws Unrecognized attribute 'crossDomainScriptAccessEnabled', so that didn't work. So I implemented the IDispatchMessageInspector method. Is there good way to test the service is reporting the correct response headers back when 'OPTIONS' are requested? I tried https://www.test-cors.org, but it reports XHR status: 0 XHR status text: "" when the IDispatchMessageInspector returns the response header and maybe that's ok. not sure. Just need a way to verify the service is supporting CORS mode now. –  Jul 01 '20 at 12:40
  • In my update I verified that this solution supports CORS. – Ding Peng Jul 02 '20 at 02:25
  • After implementing the IDispatchMessageInspector interface, we need to apply it to the service. You can refer to the second link I gave for details. – Ding Peng Jul 02 '20 at 04:51