lundi 5 août 2019

asp.net webform Access-controll alow orgin not working?

I have asp.net webform project. In button click event I call javascript method to perfomr xmlhttprequest to get all country name json. I got access control allow orign error. how do I fix it. Please do not refer web api project.

enter code here


<form id="form1" runat="server">
        <div>
            <h4>Test xmlhttprequest on cors</h4>
            <input type="button" value="Get ajax cors" onclick="meth1()" />
        </div>
    </form>
    <script>
        var url = "http://country.io/names.json"
        function meth1() {
            var xmlhttp = new XMLHttpRequest();           
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.status == 200 && xmlhttp.readyState == 4) {
                console.log("ready " + this.readyState + "   status  " + this.status);
                console.log(this.response);
            }
        }
            xmlhttp.open("get", url, true);
            xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
            xmlhttp.send();
        }        
    </script>
 protected void Application_BeginRequest(object sender, EventArgs e)
        {
            var context = HttpContext.Current;                   
            context.Response.AddHeader("Access-Control-Allow-Origin", "*");
            context.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:53410/");
            context.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
            context.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
        }
enter code here




Aucun commentaire:

Enregistrer un commentaire