Angular / ASP.NET Проблема Core 2.1 CORS

#c# #angular #asp.net-web-api #asp.net-core #cors

#c# #angular #asp.net-web-api #asp.net-core #cors

Вопрос:

Ситуация такова, что у меня было существующее приложение angular, и я меняю серверную службу на ASP.NET Ядро 2.1. Я успешно создал API и включил CORS при регистрации моей службы в файле startup.cs, но когда я пытаюсь получить доступ к любому конкретному URL-адресу моего api, появляется это сообщение об ошибке

Доступ к XMLHttpRequest в ‘https://localhost:44329/api/ThinkTank/Index ‘ из источника’http://localhost:4200 ‘ был заблокирован политикой CORS: заголовок ‘Access-Control-Allow-Origin’ отсутствует в запрошенном ресурсе

Я думаю, что это проблема с моей начальной страницей, поэтому я разместил ее ниже

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace CPDEPCoreApi
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        readonly string MyAllowSpecificOrigins = "https://localhost:44329";
        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy(MyAllowSpecificOrigins,
                builder =>
                {
                    builder.WithOrigins("https://localhost:44329")
                    .AllowAnyHeader()
                    .AllowAnyMethod(); ;
                });
            });
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }
            app.UseCors(MyAllowSpecificOrigins);
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
  

Заранее спасибо за вашу помощь.

Ответ №1:

Ваш источник localhost:4200 не localhost:44329 (это ваш сервер).

Измените эту строку builder.WithOrigins("https://localhost:44329") на builder.WithOrigins("http://localhost:4200")

Комментарии:

1. @Geeksan Каков ваш текущий Startup.cs ?