【问题标题】:ASP.NET Core API Enabling Cors not working启用 Cors 的 ASP.NET Core API 不起作用
【发布时间】:2021-02-22 04:04:28
【问题描述】:

第一次尝试使用 asp.net core 制作 api,我使用的是 ASP.NET Core 3.1。当我尝试发送 GET 请求时遇到此控制台错误:

Access to XMLHttpRequest at 'https://localhost:5001/api/items/1' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. 

我在这个网站和其他网站上尝试了很多解决方案,但它们似乎并不适合我。 这是我的 Javascript 方面的内容:

const sendRequest = async function(url) {
    try {
        let response = await axios.get(url);
        return response;
    } catch (error) {
        console.error(error);
        return [];
    }
};

这是我在 Startup.cs 中的内容

public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy("AllowMyOrigin",
                builder => builder.WithOrigins(
                    "http://localhost:8080/")
                    .WithMethods("POST", "GET", "PUT")
                    .WithHeaders("*")
                    );
            });
            services.AddDbContext<DBContext>(opt =>
            opt.UseSqlServer(Configuration.GetConnectionString("DatabaseName")));
            services.AddControllers();
            
            
        }

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            
            //app.UseAuthentication();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();
            app.UseCors("AllowMyOrigin");
            //app.UseAuthorization();
            //app.UseAuthentication();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

如果信息太少,我会尝试澄清,但就像我说的,这是我第一次做这样的事情来处理 cors 政策。

【问题讨论】:

    标签: javascript c# asp.net-core cors


    【解决方案1】:

    builder.WithOrigins("http://localhost:8080/")

    请注意,指定的 URL 不能包含尾部斜杠 (/)。请修改如下代码,然后检查它是否运行良好。

    services.AddCors(options =>
    {
        options.AddPolicy("AllowMyOrigin",
            builder => builder.WithOrigins(
                "http://localhost:8080")
            .WithMethods("POST", "GET", "PUT")
            .AllowAnyHeader()
            );
    });
    

    【讨论】:

      【解决方案2】:

      请尝试在里面添加这个

      public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
      {
      app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-12-01
        • 1970-01-01
        • 2019-02-11
        • 1970-01-01
        • 1970-01-01
        • 2020-09-02
        • 1970-01-01
        • 2017-11-12
        相关资源
        最近更新 更多