Frank Rosario
Frank Rosario

Reputation: 2661

Add custom response header; header gets lost when a service calls throws an exception

I have the following code in my global.asax.cs, to enable cross domain AJAX requests for certain domains:

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        string whiteList =
            System.Configuration.ConfigurationManager.AppSettings["AjaxCrossDomainWhitelist"];

        if (!string.IsNullOrWhiteSpace(whiteList))
        {

            string[] whiteListDomains = whiteList.Split(';');

            string origin = Request.Headers["origin"];

            if (!string.IsNullOrEmpty(origin))
            {
                origin = origin.ToLower();

                foreach (string domain in whiteListDomains)
                {
                    if (domain.ToLower() == origin)
                    {
                        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", domain);
                        break;
                    }
                }
            }



            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {

                //These headers are handling the "pre-flight" OPTIONS call sent by the browser
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                //Access Control policy has a lifetime of one hour
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "3600");
                HttpContext.Current.Response.End();
            }
        }

    }

When one of the web services called on the website returns successfully, the "Access-Control-Allow-Origin" header is sent along successfully and everything works fine. However, when a service call causes an exception; the "Access-Control-Allow-Origin" header is still added to the HttpContext.Response; I confirmed as much by trapping Application_EndRequest and checking the Response.Headers collection. However, when I check the sent response in Firebug, Chrome Dev Tools, or Charles, the "Access-Control-Allow-Origin" header was not sent and I can't figure out why.

Any pointers?

Upvotes: 3

Views: 2716

Answers (1)

Kees
Kees

Reputation: 1418

Create a HTTP module and register it in your web.config instead of doing this in global.asax See msdn link

Upvotes: 2

Related Questions