locked
No 'Access-Control-Allow-Origin' header is present on the requested resource. RRS feed

  • Question

  • User1324715958 posted

    I'm not sure what I need to do in my API to return a header to people requesting access. This is the error they are getting currently:

    has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

    Here is my Unity WebGL client requesting access to the API

    IEnumerator GetJsonContent(string url, string bodyJsonString)
        {
            var request = UnityWebRequest.Post(url, "{}");
            request.method = "POST";
    
            byte[] bodyRaw = Encoding.UTF8.GetBytes(bodyJsonString);
            request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
            request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
            txtDebug.text = "Access-Control-Allow-Origin: *";
            request.SetRequestHeader("Access-Control-Allow-Origin", WBG_Config._EndPoint);
            txtDebug.text = "Access-Control-Allow-Origin: true";
            request.SetRequestHeader("Access-Control-Allow-Credentials:", "true");
            txtDebug.text = "Content type json";
            request.SetRequestHeader("Content-Type", "application/json");
            
    
            txtDebug.text = "Sent";
            yield return request.SendWebRequest();
            txtDebug.text = "Returned";
            while (!request.isDone)
            {
                yield return new WaitForEndOfFrame();
            }
    
            if (request.isNetworkError)
            {
                txtDebug.text = request.error;
                Debug.Log(request.error);
            }
            else
            {
                //var jsonContent = request.downloadHandler.text;
    
                var response = request.downloadHandler.data;
                string json = System.Text.Encoding.UTF8.GetString(response);
                var _Response = JsonConvert.DeserializeObject<WBGString>(json);
    
                txtResponse.text = _Response.Http_Response;
            }
    
            yield break;
        }

    I thought I fixed the issue by adding these lines:

            request.SetRequestHeader("Access-Control-Allow-Origin", WBG_Config._EndPoint);
            request.SetRequestHeader("Access-Control-Allow-Credentials:", "true");

    But the problem remains. I've read I can adjust on my API end as well to return the domain so CORS will stop complaining. Not sure what I need to do on the API. Its a ASP MVC API I built awhile ago. All my apps use it so I'm a little scared to make a update unless I know for sure its the right solution 

    Friday, January 15, 2021 4:24 PM

All replies

  • User475983607 posted

    I think you misunderstand CORS.  CORS is a browser security feature that does not allow JavaScript to code to make a cross origin request unless the cross origin application allows the request.  Therefore, CORS must be enable in the Web API application that is hosting the GetJsonContent() action.  The unity post is not affected by CORS.  

    https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api

    If CORS is enabled correctly, then the common problem is an exception on Web API that causes an error response.  The error response is not CORS enabled which cause the browser to show the CORS error.  The good news is even though there is a CORS error you can still see the response from the service.  Just open the browser's dev tools, network, and click on the request.  From here you can get to the response and the error message.

    Friday, January 15, 2021 6:51 PM
  • User1324715958 posted

    GetJsonContent is from the Unity application. It sent a request to the API. The API is returning the data but something is blocking the data on the app side. Trying to figure out how to accept the data. CORS I thought was blocking it based on error. 

    Friday, January 15, 2021 7:33 PM
  • User1324715958 posted

    Updated code here is new error:

    Access to XMLHttpRequest at 'http://www.whiteboxgaming.xyz:34188/api/WhiteBoXGaming/Post_TestAPI' from origin 'http://whiteboxgaming.infinityfreeapp.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

    Here is the c# code sending the request to the API::

    IEnumerator GetJsonContent(string url, string bodyJsonString)
        {
            string EndPoint = WBG_Config._EndPoint;
            var request = UnityWebRequest.Post(url, "{}");
            request.method = "POST";
            byte[] bodyRaw = Encoding.UTF8.GetBytes(bodyJsonString);
    
            try
            {
                request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
                request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
                txtDebug.text = "Access-Control-Allow-Origin: *";
                request.SetRequestHeader("Access-Control-Allow-Origin", EndPoint);
                //txtDebug.text = "Access-Control-Allow-Origin: true";
                //request.SetRequestHeader("Access-Control-Allow-Credentials:", "true");
                txtDebug.text = "Content type json";
                request.SetRequestHeader("Content-Type", "application/json");
            }
            catch (Exception ex)
            {
                Debug.Log(ex.Message);
            }       
            
            txtDebug.text = "Sent";
            yield return request.SendWebRequest();
            txtDebug.text = "Returned";
            while (!request.isDone)
            {
                yield return new WaitForEndOfFrame();
            }
    
            if (request.isNetworkError)
            {
                txtDebug.text = request.error;
                Debug.Log(request.error);
            }
            else
            {
                //var jsonContent = request.downloadHandler.text;
    
                var response = request.downloadHandler.data;
                string json = System.Text.Encoding.UTF8.GetString(response);
                var _Response = JsonConvert.DeserializeObject<WBGString>(json);
    
                txtResponse.text = _Response.Http_Response;
            }
    
            yield break;
        }
    

    Do I need to do something on my API side to resolve this or help resolve this?

    Edit:

    I think I see what your saying now. So how do I fix this?

    Friday, January 15, 2021 7:36 PM
  • User475983607 posted

    According to the screenshot, the browser made an HTTP request that resulted in a a 405 (Method not allowed) response.  The browser threw the CORS error because the 405 response is not CORS enabled. 

    There is not enough information to determine if the problem is in the JavaScript code making the request, the Web API, or the code you've shared.  IMHO, the code you have shared is a little unusual the way it handles JSON and streams.

    Friday, January 15, 2021 8:34 PM
  • User-474980206 posted

    before the browser makes the CORS POST request, it first requests the url with the OPTION method to get the CORS policy. You need to add support for the OPTION method for your action and respond with the proper CORS headers.

    be sure the OPTION method is mapped to MVC. 

    Friday, January 15, 2021 8:53 PM