White Whale Studio

Asp.net MVC API와 연결시 Cors 문제 해결 본문

IT Engineering/Vue.js

Asp.net MVC API와 연결시 Cors 문제 해결

glorymind 2020. 2. 20. 09:43
반응형

Vue로 구현을 하다보면 CORS 오류가 뜨는 경우가 있습니다.

CS환경에서만 구현해와서 웹 쪽 지식이 적은 저로서는 도무지 이해가 안되는 보안 규정이라던가

규칙이라던가 그런것들이 많네요.

 

사실 Vue에 한정된것이 아니라 자바스크립트 계열 언어인 리액트나 다른 쪽에서도 API호출시 발생할수 있는 문제라고 하네요.

우선 로그 성격으로 블로그를 포스팅합니다.

 

사실 Vue보다는 서버 쪽인 ASP.net 쪽 API 프로젝트를 수정해줘야합니다.

 

Web.Config 파일에서

 

1
2
3
4
5
6
7
8
9
10
11
12
13
<system.webServer>
   <modules runAllManagedModulesForAllRequests="true">
   </modules>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="http://localhost:8080" />        
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
        <add name="Access-Control-Allow-Credentials" value="true" />
      </customHeaders>
    </httpProtocol>
</system.webServer>
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

위의 소스를 configuration에 추가합니다.

Access-Conrtrol-Allow-Origin 항목에 있는 IP가 허용을 해줄 IP입니다.

저의 경우는 테스트 용으로 구현하다가 안되서 로컬 IP를 허용하기위해 사용했습니다.

 

또한 추가적으로 Global.asax.cs 파일에다가는 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 protected void Application_BeginRequest(Object sender, EventArgs e)
        {
            // Preflight request comes with HttpMethod OPTIONS
            // The following line solves the error message
            //HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:8080");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Cache-Control""no-cache");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods""GET, POST");
                // If any http headers are shown in preflight error in browser console add them below
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers""Content-Type, Accept, Pragma, Cache-Control, Authorization ");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age""1728000");
                HttpContext.Current.Response.End();
            }
        }
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

요로코롬 추가를 해줍니다.

 

이 방법도 통하지않는 다면.. 에러 메시지에 맞춰서 구글링을 추천드립니다.

 

반응형
Comments