【问题标题】:I'm getting CORS error with CORS configured on ASP.NET Core Web API app在 ASP.NET Core Web API 应用程序上配置 CORS 时出现 CORS 错误
【发布时间】:2021-12-20 08:49:12
【问题描述】:

我有一个托管在 Azure 中的 ASP.NET Core Web API。当我尝试从托管在 Vercell 上的网络应用发出获取请求时,我收到了以下错误:

CORS 政策已阻止从源“https://{myapp}.vercel.app”获取{myapi enpoint} 的访问权限:
对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

这是我的Startup.cs 文件:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Cors;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using Pomelo.EntityFrameworkCore.MySql;
using System.Threading.Tasks;
using ctsapi.Services;
using Jose;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using ctsapi.Models;
using Newtonsoft.Json.Linq;
using Microsoft.AspNetCore.Http;
using System.Net;
 
namespace ctsapi
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
 
        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("AllowAllOrigins", builder =>
                {
                    builder.AllowAnyOrigin();
                    builder.AllowAnyMethod();
                    builder.AllowAnyHeader();
                });
            });
            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "ctsapi", Version = "v1" });
                //c.IncludeXmlComments(XmlCommentsPath.XmlCommentsFilePath);
            });
 
            var jwtSection = Configuration.GetSection("JWTSettings");
            services.Configure<JWTSettings>(jwtSection);
 
            //to validate the token which has been sent by clients
            var appSettings = jwtSection.Get<JWTSettings>();
            var key = Encoding.ASCII.GetBytes(appSettings.SecretKey);
 
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
                .AddJwtBearer(x =>
                {
                    x.RequireHttpsMetadata = true;
                    x.SaveToken = true;
                    x.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                    {
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = new SymmetricSecurityKey(key),
                        ValidateIssuer = false,
                        ValidateAudience = false
                    };
                });
 
            services.AddAuthorization(options =>
            {
                options.AddPolicy(Policies.Admin, Policies.AdminPolicy());
                options.AddPolicy(Policies.ShopKeeper, Policies.ShopKeeperPolicy());
                options.AddPolicy(Policies.User, Policies.UserPolicy());
            });
        }
 
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseDefaultFiles();
            app.UseStaticFiles(); // dodanie wwwroot
            //if (env.IsDevelopment())
            //{
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "ctsapi v1"));
            //}
 
            app.UseHttpsRedirection();
 
            app.UseRouting();
 
            app.Use(async (context, next) =>
            {
                await next();
 
                if (context.Response.StatusCode == (int)HttpStatusCode.Unauthorized)
                {
                    // "Token Validation Has Failed. Request Access Denied"
                    context.Response.ContentType = "application/json";
                    await context.Response.WriteAsync(new ErrorDto()
                    {
                        StatusCode = 401,
                        Message = "Token Validation Has Failed. Request Access Denied"
                    }.ToString());
                }
            });
 
            app.UseCors("AllowAllOrigins");
 
            app.UseAuthorization();
 
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

知道为什么会这样吗?

我的网络应用框架是 Next.js。

这是我的 Azure 配置:

  • 默认部署配置文件(WebApp 托管在 F1 层的 Windows 机器上)
  • 我什至更改了 web.config 文件以始终发送所需的标头

【问题讨论】:

  • 邮递员请求也很有效 - 邮递员不关心 CORS
  • 这只是应该告诉端点没问题或smth的信息
  • 在 Azure 管理门户中配置 CORS,而不是在您的代码中
  • 我什至用 web.config 文件强制它,但 next.js 应用程序看不到它
  • 看看这个答案....它解释了一些关于飞行前请求的事情。 stackoverflow.com/questions/69197165/…

标签: c# asp.net-core next.js asp.net-core-webapi


【解决方案1】:

尝试使用这种语法

public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(o => o.AddPolicy("AllowAnyOrigin",
                      builder =>
                       {
                       builder.AllowAnyOrigin()
                              .AllowAnyMethod()
                              .AllowAnyHeader();
              }));

        .....
            
        }

        
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            .....

           // app.UseRouting();

            app.UseCors("AllowAnyOrigin");

         //  app.UseAuthorization();
         // app.UseEndpoints(..
 
         }

确保 UseCors 应该在 Configure 方法的末尾,但在 UseAuthorizaton 之前。 AddCors 应该位于配置服务的顶部。

【讨论】:

  • 我将尝试使用此服务配置,app.UseCors("AllowAnyOrigin") 已经在正确的位置
  • 还是这个错误
  • @PanMichal 如果你真的需要帮助,把你所有的启动代码配置方法贴出来。还有一些规则
  • 整个 Startup.cs 已发布
  • @PanMichal 谢谢,一切似乎都很好,但 Cors 非常棘手。我从未见过有人使用 app。与 Cors 一起使用,因此您可以尝试将其与 Cors 交换,但我不确定它是否会起作用。
【解决方案2】:

所以看起来后端的框架只是有一些问题(我不知道如何描述它)。当我重新启动我的电脑,然后重建我的应用程序时,一切正常。

感谢大家的每一条评论?

【讨论】:

    猜你喜欢
    • 2018-01-01
    • 2021-01-03
    • 2023-01-12
    • 2019-11-09
    • 2019-09-09
    • 2017-12-04
    • 2017-04-26
    • 2019-12-07
    • 2020-07-26
    相关资源
    最近更新 更多