RestAPI 호출시 발생한 ajax Error 0




문제는 CORS 설정때문이었다.


Cors 에 대한 내용을 추가해주자...



Startup.cs


    public class Startup

    {

        public IConfiguration Configuration { get; set; }


        public Startup(IConfiguration configuration)

        {

            Configuration = configuration;

        }


        // This method gets called by the runtime. Use this method to add services to the container.

        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940

        public void ConfigureServices(IServiceCollection services)

        {

            // services.AddMvc(); 보다 앞에 위치 시킨다. (이건 Test 해보지 않았다. ^^;)

            services.AddCors();


            services.AddMvc();


            services.AddDataAccess();

            services.AddBusinessLogics();


            var configBuilder = new ConfigurationBuilder()

               .SetBasePath(Directory.GetCurrentDirectory())

               .AddJsonFile("appsettings.json", optional: true);

            var config = configBuilder.Build();


            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

        }


        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)

        {

            if (env.IsDevelopment())

            {

                app.UseDeveloperExceptionPage();

            }


            // app.UseMvc(); 보다 앞에 위치 시킨다.

            app.UseOptions();


            //app.UseCors(builder => 

            //    builder.AllowAnyOrigin()

            //    .AllowCredentials()

            //    .AllowAnyHeader()

            //    .AllowAnyMethod()

            //    //.WithMethods("POST,GET,PUT,PATCH,DELETE,OPTIONS")

            //);


            //app.UseCors(builder =>


            //    //builder.AllowAnyOrigin().AllowAnyMethod()

            //    //.WithHeaders(HeaderNames.ContentType, "Authorization", "X-Requested-With")

            

//    builder.WithOrigins("*")

            //    //.AllowAnyOrigin()

            //    .AllowCredentials()

            //    .WithMethods("POST,GET,PUT,PATCH,DELETE,OPTIONS")

            //    .AllowAnyHeader()

            //    //.WithHeaders("Authorization", "X-Requested-With")

            //    );


            app.UseMvc();


            app.UseMvcWithDefaultRoute();


        }

    }



OptionsMiddleware.cs

    public static class OptionsMiddlewareExtensions

    {

        public static IApplicationBuilder UseOptions(this IApplicationBuilder builder)

        {

            return builder.UseMiddleware<OptionsMiddleware>();

        }

    }


    public class OptionsMiddleware

    {

        private readonly RequestDelegate _next;

        private IHostingEnvironment _environment;


        public OptionsMiddleware(RequestDelegate next, IHostingEnvironment environment)

        {

            _next = next;

            _environment = environment;

        }


        public async Task Invoke(HttpContext context)

        {

            this.BeginInvoke(context);

            await this._next.Invoke(context);

        }


        private async void BeginInvoke(HttpContext context)

        {

            //context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            ////context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*", (string)context.Request.Headers["Origin"] });

            ////context.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "Origin, X-Requested-With, Content-Type, Content-Type: application/json, Accept, Accept: application/json, Authorization" });

            //context.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "*" });

            //context.Response.Headers.Add("Access-Control-Allow-Methods", new[] { "GET, POST, PUT, DELETE, OPTIONS" });

            //context.Response.Headers.Add("Access-Control-Allow-Credentials", new[] { "true" });


            context.Response.Headers.Add("Access-Control-Allow-Origin", "*");

            context.Response.Headers.Add("Access-Control-Allow-Credentials", "true");

            // Added "Accept-Encoding" to this list

            //context.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "*" });

            context.Response.Headers.Add("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Requested-With, Accept, Accept-Version, Accept-Encoding, Content-Encoding, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name");

            context.Response.Headers.Add("Access-Control-Allow-Methods", "POST,GET,PUT,PATCH,DELETE,OPTIONS");


            if (context.Request.Method == "OPTIONS")

            {

                //context.Response.StatusCode = 200;

                //await context.Response.WriteAsync("OK");


                context.Response.StatusCode = (int)HttpStatusCode.OK;

                await context.Response.WriteAsync(string.Empty);

            }


        }

    }



Startup.cs 에서 


            .AllowAnyMethod() 대신 


            .WithMethods("POST,GET,PUT,PATCH,DELETE,OPTIONS") 로 변경해 보았는데.



Origin 과는 전혀 상관없는 오류가 발생했다. ㅡㅡ;

그렇다면 모든 Methos 를 열어줘야 한다는 이야기가 되는데... 그럼 안되겠죠? ㅋㅋ


그래서 app.UseCors(....) 를 사용하지 않고 위에 적어 놓은 Middleware 를 사용하기로 결정했다. 

Origins 의 경우는  Test 를 거쳐 변경할 예정이다.

Headers 의 경우도 현재는 Authorization, Content-Type, X-Requested-With 만 필요하지만 일단 다른 Header 들도 추가해 놓은 상태다.



ASP.NET Core 의 경우 ASP.NET 보다 유연하겠구나 라는 생각이 들긴하지만 서비스 내용을 바탕으로 설정해줘야 할 것들을 숙지하고 해둬야 하겠다.


이젠 WebSocket 을 붙여야 하는 상황인데...

Test 를 해보니 Socket 으로 가야할 녀석이 Controller 로 Routing 되는 걸 알게 되었다.


그럼 이만 Socket Test 하러... 슝~!




행복한 고수되셔요.


woojja ))*

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

반응형

+ Recent posts