繁体   English   中英

带有POST请求的asp.net Web API角度CORS预检问题

[英]asp.net web api angular CORS preflight issue with POST requests

我有一个配置为使用WINDOWS AUTHENTICATION的webapi。

var cors = new EnableCorsAttribute(origen, "*", "*") { SupportsCredentials = true };
            config.EnableCors(cors);

在我的角度应用程序中,我有以下几种方法:

GET方法工作完美。

result.CargarAreas = function (callBack, onError) {

        //url = WebApi + "Personas";
        var url = constants.apiPath + "Areas";

        //$http.get(url, { headers: { "Access-Control-Allow-Origin": constants.serverPath } })
        $http.get(url, {
            withCredentials: true
        })
        .then(function (data) {
            callBack(data);
        })
        .catch(function (data) {
            onError(data);
        });
    };

POST方法给我这个错误:

result.GuardarContacto = function (callBack, onError, data) {

        //url = WebApi + "Contactos";
        var url = constants.apiPath + "Contactos";

        $http.post(url, data, { headers: { "Access-Control-Allow-Origin": constants.serverPath } })

        .then(function (data) {
            callBack(data);
        })
        .catch(function (data) {
            onError(data);
        });
    };

最后是Web api方法

[HttpGet]
        [Route("api/AutenticationSite")]
        public IHttpActionResult AutenticationSite()
        {
            string user = HttpContext.Current.Request.LogonUserIdentity.Name.ToString();
            string[] subUser = user.Split('\\');
            bool respuesta = UsuariosDao.Authorize(subUser[1]);

            if (respuesta == true)
            {
                return Ok("Authenticated: " + user);
            }
            else
            {
                return BadRequest("Not authenticated" );
            }
        }

以及我们一直在努力解决的DAMN错误:

XMLHttpRequest无法加载http:// abcom / api / Contactos 对预检请求的响应未通过访问控制检查:请求的资源上不存在“ Access-Control-Allow-Origin”标头。 因此,不允许访问来源“ http:// abcom ”。 响应的HTTP状态码为401。

更新1

有关请求和响应的信息

请求URL: http:// abcom / api / Contactos请求方法:OPTIONS状态码:200 OK远程地址:181.143.YY.XX:80引用者策略:no-referrer-when-downgrade响应标题(11)请求标题查看源接受: /接受编码:gzip,放气,sdch接受语言:es-ES,es; q = 0.8 Access-Control-Request-Headers:content-type Access-Control-Request-Method:POST Cache-Control:no -cache连接:keep-alive主机:abcom来源: http:// abcom语法 :no-cache参考网址:http://abcom/Index.html User-Agent:Mozilla / 5.0(Windows NT 10.0

在此处输入图片说明

删除角度代码中的访问控制标头设置。 似乎您已在多个位置设置了此标头,因此尽管您的Web API代码启用了cors,但输出却没有。

密切注意,提防,小心

  • web.config => httpRuntime => httpHandlers =>标头被设置
  • MVC.CORS NuGet的用法,而不是WebAPI.CORS包的用法。 在这里,您需要使用一个WebAPI(尽管它取决于MVC,所以请不要将其卸载)
  • 无需在global.asax中更改OPTIONS动词处理程序
  • 多次调用在不同的地方config.EnableCors(Global.asax中和webapi.config)。 在您的来源中搜索“ cors”只是为了确保这一点。
  • 检查是否在全局级别或控制器/操作级别上设置了属性。 您的特定操作可能已被排除在外。 尝试在其他控制器上发表文章,以确保
  • 变量“ origen”正确存储了客户端的IP地址和端口。 任何偏差都将导致不发送标题。 尝试使用star *而非特定客户端进行测试。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM