Angularjs没有'Access-Control-Allow-Origin'标头出现在请求的资源上

时间:2017-11-12 09:05:10

标签: c# angularjs json

我得到错误:

  

无法加载http://localhost:10948/Api/Home/PostData/[object%20Object]:请求的资源上没有“Access-Control-Allow-Origin”标头。因此,不允许原点“http://localhost:57580”访问。响应的HTTP状态代码为404.

即使我的WebAPi(Global.asax.cs)文件中有Access-controll Orion文件

 protected void Application_BeginRequest()
        {
            string[] allowedOrigin = new string[] { "http://localhost:57580", "http://localhost:11518" };
            var origin = HttpContext.Current.Request.Headers["Origin"];
            if (origin != null && allowedOrigin.Contains(origin))
            {
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", origin);
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET,POST");
            }

Angular.js

$scope.SubmitForm = function (isValied) {
        var EmployeeDetails = {
            'Empname': $scope.Emp.EmpName
        }
        if (isValied) {
       EmployeeFactoryService.SaveEmployeee(EmployeeDetails).then(function ()

            })
        }       
    }

Factory.Js

EmployeeFactoryServices.SaveEmployeee = function (Employee) {
    return $http({
        url: 'http://localhost:10948/Api/Home/PostData/'+ Employee,
        method: 'POST',
        ContentType: 'application/x-www-form-urlencoded', })

3 个答案:

答案 0 :(得分:1)

更改配置CORS的方式如下,

  HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            //These headers are handling the "pre-flight" OPTIONS call sent by the browser
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, OPTIONS");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
            HttpContext.Current.Response.End();
        }

请求也应该是,

 return $http({
        url: 'http://localhost:10948/Api/Home/PostData/'+ ,
        method: 'POST',
        data : Employee,
        ContentType: 'application/json' })

答案 1 :(得分:0)

有一个chrome扩展cors。 使用它,你很高兴。

答案 2 :(得分:0)

1-我可以从您的网址中看到您尝试发送的对象没有进行字符串化,因此我建议使用JSON.stringify(EmployeeDetails)对其进行字符串化

2-您最好使用Content-Type:application/json来处理您的帖子请求。

3-您必须允许客户端应用程序的请求进入您的后端代码

4-您可以通过this extension

暂时解决此问题
相关问题