locked
webservice 'Access-Control-Allow-Origin' header is present on the requested resource RRS feed

  • Question

  • User450763225 posted

    Hi, I placed webservice in my local IIS, why it keeps reporting this error ('Access-Control-Allow-Origin' header is present on the requested resource) even if I access from local. I attached the html code and webservice code. please help. By the way, my webservice should be good, I tested and got the result

    <!DOCTYPE HTML>
    <html>
    <head>
    <script type="text/javascript" src="jquery-2.1.4.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){
    
    $('#click').click(function(){
    
    $.ajax({
        type: "GET",
        url: "http://localhost:8080/echartService.asmx/getechart",
        // The key needs to match your method's input parameter (case-sensitive).
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data){alert(data);},
        failure: function(errMsg) {
            alert(errMsg);
        }
    });
    
    
    
    
    });
    });
    </script>
    </head>
    <body>
    <button id="click" type="button">click me</button>
    <div id="info"></div>
    </body>
    </html> 
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Services;
    using System.Web.Script.Services;  
    using echart_test;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Json;
    using Newtonsoft.Json;
    using Newtonsoft;
    
    namespace echart_test
    {
        /// <summary>
        /// Summary description for echartService
        /// </summary>
        //[WebService(Namespace = "http://tempuri.org/")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
        [System.ComponentModel.ToolboxItem(false)]
        // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
        [System.Web.Script.Services.ScriptService]
        public class echartService : System.Web.Services.WebService
        {
            private Service_PerformaceEntities db = new Service_PerformaceEntities();
            [WebMethod]
            public void HelloWorld()
            {
                
            }
    
            public IEnumerable<echart_test> getInvoice()
            {
                return db.echart_test.AsEnumerable();
            }
    
    
    
            [WebMethod(Description = "return pure JSON")]
            [ScriptMethod(UseHttpGet = true)] 
            public string getechart()
            {
                List<echart_test> echart = (from d in getInvoice()
                                              select d).ToList() ;
    
                string json = JsonConvert.SerializeObject(echart,Formatting.Indented);
                return json;
                
            }
        }
    }
    



    Friday, September 4, 2015 10:25 PM

Answers

  • User475983607 posted

    This is a Cross-site HTTP requests (CORS) error and can be a bit confusing when you first run across it.  

    The browser sees the AJAX service URL is on a domain than the original request that rendered the current page.  The browser sends an OPTION request to the domain to make sure it is OK to request a resource from this domain.

    The following is an OPTIONS requests sent from the client browser asking if it is OK to send an HTTP POST from the origin http://localhost.

    OPTIONS http://localhost:46579/ClassicWebService.asmx/HelloWorld HTTP/1.1
    Host: localhost:46579
    Connection: keep-alive
    Access-Control-Request-Method: POST
    Origin: http://localhost
    User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36
    Access-Control-Request-Headers: accept, content-type
    Accept: */*
    Referer: http://localhost/TestingWeb/AjaxCors.aspx
    Accept-Encoding: gzip, deflate, sdch
    Accept-Language: en-US,en;q=0.8,es;q=0.6
    

    The following is an example server response where the service is not CORS aware (default).

    HTTP/1.1 200 OK
    Allow: OPTIONS, TRACE, GET, HEAD, POST
    Server: Microsoft-IIS/10.0
    Public: OPTIONS, TRACE, GET, HEAD, POST
    X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcTWljaGFlbFxEb2N1bWVudHNcVmlzdWFsIFN0dWRpbyAyMDEyXFByb2plY3RzXERlbW9zXFRlc3RpbmdXZWJcQ2xhc3NpY1dlYlNlcnZpY2VcQ2xhc3NpY1dlYlNlcnZpY2UuYXNteFxIZWxsb1dvcmxk?=
    X-Powered-By: ASP.NET
    Date: Sat, 05 Sep 2015 11:51:28 GMT
    Content-Length: 0
    

    And an example response when the service is CORS aware.

    HTTP/1.1 200 OK
    Allow: OPTIONS, TRACE, GET, HEAD, POST
    Server: Microsoft-IIS/10.0
    Public: OPTIONS, TRACE, GET, HEAD, POST
    X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcTWljaGFlbFxEb2N1bWVudHNcVmlzdWFsIFN0dWRpbyAyMDEyXFByb2plY3RzXERlbW9zXFRlc3RpbmdXZWJcQ2xhc3NpY1dlYlNlcnZpY2VcQ2xhc3NpY1dlYlNlcnZpY2UuYXNteFxIZWxsb1dvcmxk?=
    X-Powered-By: ASP.NET
    Access-Control-Allow-Headers: accept, content-type
    Access-Control-Allow-Origin: http://localhost
    Access-Control-Allow-Methods: POST, GET, OPTIONS
    Date: Sat, 05 Sep 2015 11:56:54 GMT
    Content-Length: 0
    

    Access-Control-Allow-Headers - this means each request requires an accept and content-type header.

    Access-Control-Allow-Origin - allow the http://localhost origin to make the request

    Access-Control-Allow-Methods - allow GET, POST, and OPTIONS requests

    The browser reads the CORS aware response and sees it is ok to send the service request.  This process took two request/responses.  The OPTION request followed by the actual service request.

    In order to configure the service to accept a CORS request simply update the web.config.

      <system.webServer>
        <httpProtocol>
          <customHeaders>
            <add name="Access-Control-Allow-Headers" value="accept, content-type" />
            <add name="Access-Control-Allow-Origin" value="http://localhost" />
            <add name="Access-Control-Allow-Methods" value="POST, GET, OPTIONS" />
          </customHeaders>
        </httpProtocol>
      </system.webServer>

    If updating the web.config does not work then add a global.asax file and update the Application_BeginRequest event as below.  I've seen where folks have trouble configuring the web.config - not sure why...

    void Application_BeginRequest(object sender, EventArgs e)
    {
    	var context = HttpContext.Current;
    	var response = context.Response;
    	
    	// enable CORS
    	response.AddHeader("Access-Control-Allow-Origin", "*");
    	
    	if (context.Request.HttpMethod == "OPTIONS")
    	{
    		response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
    		response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
    		response.End();
    	}
    }

    Notice Access-Control-Allow-Origin: "*". this means accept requests from any domain.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, September 5, 2015 8:13 AM