2

I have a WebService (.asmx) page with many functions I want to run from another webpage. The webpages I want to use ajax in to call the functions are from a different origin than the web service. When I try the following ajax call:

$.ajax({
        type: "POST",
        url: "http://192.168.18.218/WebSite/Pages/DBQuery.asmx/GetTestList",
        crossDomain: true,
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({
            'filterID': 0
        }),
        dataType: "json",
        success: function (data)
        {
            data = JSON.parse(data.d);
            console.log(data);
        }
    });

I get the following error:

XMLHttpRequest cannot load http://192.168.18.218/WebSite/Pages/DBQuery.asmx/GetTestList. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 404.

I can use that exact link provided as the url on a browser on the same machine as where the web service is being hosted and everything works as expected. Using this ajax call from internet explore 11 or edge works fine as well, but when running the command from google chrome it gives the above error.

Reading up it seems like this is an issue with my web service not adding in the right fields to its response packets for CORS, so the google chrome setting catches it and throws an error. I have tried to code used for web API's to enable CORS (see the following code block).

public static void Register(HttpConfiguration config)
    {
        //TODO: determine acceptable origins
        var corsAttr = new EnableCorsAttribute("*", "*", "*"); //accept all origins, headers, and methods
        config.EnableCors(corsAttr); //enable cross origin requests
    }

This did not seem to work and I cannot find documentation for this issue using web services instead of web APIs. How do I fix the web service and or ajax calls to enable CORS correctly?

EDIT Adding the following lines of code to the web config file fixes the issue with the CORS portion of the header not being added:

    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Headers" value="*" />
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Methods" value="*" />
      </customHeaders>
    </httpProtocol>

However, I still am getting a 404 error. Testing the ajax call on the machine hosting the web service, the ajax works correctly and as expected. However when running it cross origin, I get the 404 error.

1 Answer 1

1

Even after adding the custom headers to the web config the 404 error remained. This ended up being due to the header still not being fully correct or ISAPI intercepting packets with the OPTIONS verb and causing some issues I never figured out the exact cause. My solution was to remove the changes to the web config and add a Global asax file with the following code:

<%@ Application Language="C#"%>

<script RunAt="server">
    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();
        }
    }
</script>

This makes sure the packets have the right headers. You have to remove the pieces of the web config I mentioned in my question as it will add them twice which will cause the ajax call to fail as well.

Sign up to request clarification or add additional context in comments.

1 Comment

In 2021 this still worked for me. It is a straight forward solution, I must bring attention to the point that you have to remove duplicate information from the web.config file and it worked. As i was needing to use webservices for an android application backend.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.