Search code examples
angularjscross-domainhttphandlerashx

Download PDF Document using Httphandler from AngularJS


I have developed a httpHandler to fulfill my PDF download which uses angularJS. It was working fine until i moved the service part into different domain. When i moved the service part into different domain than my UI AngularJS application, it start giving following error.

XMLHttpRequest cannot load http://localhost:57072/DocumentHandler.ashx?Caller=1&token=1. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:54470' is therefore not allowed access. The response had HTTP status code 500.

Here is my HttpHandler method.

  public void ProcessRequest(HttpContext context)
        {

            response.Clear();
            response.ClearContent();
            response.ClearHeaders();
            response.AddHeader("Access-Control-Allow-Origin", "*");
            response.AppendHeader("Access-Control-Allow-Methods", "OPTIONS,POST,GET");
            response.AppendHeader("Access-Control-Allow-Headers", "X-File-Name,X-File-Type,X-File-Size");

            response.ContentType = MIMEType.Get(filExtension);
            response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);

            using (FileStream stream = this.Open(filesDirectory + fileName))
            {
                byte[] buffer = new byte[10240];
                int count = 0;

                while ((count = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    response.OutputStream.Write(buffer, 0, count);
                    response.Flush();
                }
            }
        }

Can any one please tell me what is wrong here?


Solution

  • This is a CORS problem. You must confugure the server to enable Cross Origin Resource Sharing. This can be done in the Web.config on the server. CORS is available in WebAPI 2.2 and you should look at porting the HttpHandler functionality to a web api controller that returns a HttpResponseMessage.