简体   繁体   中英

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

I have a webapi which is configured to use WINDOWS AUTHENTICATION.

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

In my angular app I have the follwing methods:

GET methods work perfect.

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 methods give me this error:

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);
        });
    };

and finally the web api method

[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" );
            }
        }

and the DAMN error we have been fighting for hours:

XMLHttpRequest cannot load http://abcom/api/Contactos . Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' http://abcom ' is therefore not allowed access. The response had HTTP status code 401.

UPDATE 1

Info about the request and response

Request URL: http://abcom/api/Contactos Request Method:OPTIONS Status Code:200 OK Remote Address:181.143.YY.XX:80 Referrer Policy:no-referrer-when-downgrade Response Headers (11) Request Headers view source Accept: / Accept-Encoding:gzip, deflate, sdch Accept-Language:es-ES,es;q=0.8 Access-Control-Request-Headers:content-type Access-Control-Request-Method:POST Cache-Control:no-cache Connection:keep-alive Host:abcom Origin: http://abcom Pragma:no-cache Referer: http://abcom/Index.html User-Agent:Mozilla/5.0 (Windows NT 10.0

在此处输入图片说明

Remove access-control header setting in your angular code. Looks like you have this header getting set at multiple places and thus the output is having none, despite your web api code enabling cors.

Look out for

  • web.config => httpRuntime => httpHandlers => header getting set
  • Usage of MVC.CORS NuGet 'instead' of WebAPI.CORS package. Here your need to use the WebAPI one (although it depends on MVC one so don't uninstall it)
  • No need to change the OPTIONS verb handler in global.asax
  • Multiple calls to config.EnableCors in different places (global.asax and webapi.config). Search across your source for 'cors' just to be sure on this.
  • Check if the attribute is set on a global level or controller/action level. It may be that your specific action is getting excluded. Try doing a post on some other controller to be sure
  • Variable 'origen' correctly stores the client's IP address and port. Any deviation will lead to not sending header. Try using star * rather than specific client to test.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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