1

I Have Created A WebAPI In MVC That Code Is Working Fine Am Trying To Use That Get Method In Another Project Of MVC With JQuery Function Call When Am Calling The Method Am Getting The Error is

The origin 'http://localhost:3038' is not allowed

Jquery Code

$(document).ready(function () {
$.ajax({
    type: "GET",
    url: "http://localhost:63540/api/emp",
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {

        for (var i = 0; i < data.d.length; i++) {
            $("#tbDetails").append("<tr><td>" + data.d[i].E_id + "</td><td>" + data.d[i].E_name + "</td><td>" + data.d[i].Designation + "</td><td>" + data.d[i].DepartmentName + "</td><td>" + data.d[i].E_doj + "</td><td>" + data.d[i].EmpType + "</td></tr>");
        }
    },
    error: function (result) {
        alert("Error");
    }
});
});

I Have Enabled cors for WebAPI in Like in WebApiConfig.cs file added config.EnableCors();

And In API I added

[EnableCors(origins: "http://localhost:63540", headers: "", methods: "")]

Even I Enabled CORS In API Am Getting Error,How can solve this?, Thanks.

3
  • Dont it need to be : [EnableCors(origins: "http://localhost:63540", headers: "*", methods: "*")] ? Commented Dec 21, 2016 at 7:46
  • Okay I ll try with removing this ... Commented Dec 21, 2016 at 7:47
  • I got the solution I have added astrik instead localhost in origins but it is calling two times I am calling once only first time no data is coming for the second time the data is coming so the output is not displayed how to fix this ... Commented Dec 21, 2016 at 9:59

2 Answers 2

1

try this: Add To in Global.asax.cs file "Application_BeginRequest" method

 HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
 if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
 {
     HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET");// or POST, PUT and etc.. 
     HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
     HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
     HttpContext.Current.Response.End();
 }
Sign up to request clarification or add additional context in comments.

Comments

0

[EnableCors(origins: "*", headers: "", methods: "")] I have changed origins to astrik so it is working ...

Comments

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.