【问题标题】:How to add the "Access-Control-Allow-Credentials" request header to a POST request in ASP.NET?如何将“Access-Control-Allow-Credentials”请求标头添加到 ASP.NET 中的 POST 请求中?
【发布时间】:2021-04-16 14:37:41
【问题描述】:

所以,我正在尝试使用HttpContext.Request.Headers.Add("Access-Control-Allow-Credentials", "true"); 设置“Access-Control-Allow-Credentials”,但它只适用于我的 GET 请求,但不适用于我的 POST 请求,我不知道为什么。

我也尝试在 Startup.cs 中设置它们,如下所示:

 services.AddCors(o => o.AddPolicy("ApiCorsPolicy", builder =>
            {
                builder
                       .WithOrigins("My_Web_App")
                       .AllowCredentials()
                       .AllowAnyMethod()
                       .AllowAnyHeader();
            }));

然后在Configure中使用app.UseCors("ApiCorsPolicy");

这是来自我的控制器的代码,所以我认为这里没什么特别的:

   [ApiController]
    [Route("[controller]")]
    [EnableCors("ApiCorsPolicy")]
    public class UserController : Controller
    {
        private readonly IUserService _userService;
        public UserController(IUserService userService)
        {
            _userService = userService;
        }

        [HttpPost("RegisterUser")]
        public void GetTournaments([FromBody] UserDTO user)
        {

            HttpContext.Request.Headers.Add("Access-Control-Allow-Credentials", "true");
            _userService.RegisterUser(user);
        }

    }

我的问题是,为什么我不能使用 Headers.add 方法(适用于我的 GET 请求)放置“Access-Control-Allow-Credentials”标头?如果这不是正确的方法,那么该怎么做呢? 谢谢!

编辑: 我已按要求添加了所有启动文件:

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

        public IConfiguration Configuration { get; }

      
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(o => o.AddPolicy("ApiCorsPolicy", builder =>
            {
                builder
                       .WithOrigins("http://"MyIpAddressHere"/")
                       .AllowAnyMethod()
                       .AllowAnyHeader();
            }));

            var mapperConfig = new MapperConfiguration(mc =>
            {
                mc.AddProfile(new MappingGeneral());
            });

            IMapper mapper = mapperConfig.CreateMapper();
            services.AddSingleton(mapper);

            services.AddSingleton<ITournamentService, TournamentService>();
            services.AddSingleton<IUserService, UserService>();
            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "my_app", Version = "v1" });
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "my_app v1"));
            }

            app.UseRouting();

            app.UseCors("ApiCorsPolicy");

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });


        }
    }

【问题讨论】:

  • Access-Control-Allow-Credentialsa response header
  • 它也不起作用,如果我尝试 Response.headers.add 它

标签: c# asp.net cors backend


【解决方案1】:

改变

.WithOrigins("My_Web_App")

.WithOrigins("http://localhost....") //your web app url

//your Url shouldn't end with "/" 

并从代码中删除:

//sometimes it interfers with token if you have
 .AllowCredentials()

// you don't need this at all
  HttpContext.Request.Headers.Add("Access-Control-Allow-Credentials", "true");

您的 UseCors 应该在 UseRouting 之后但在 UseAuthorization 之前。

并从您的控制器中删除:

 [EnableCors("ApiCorsPolicy")]

【讨论】:

  • 我已经对 .WithOrigins("localhost....") 进行了第一次更改,并尝试在第二步中删除它们,但仍然无法正常工作。
  • 你的网址不应该有最后一个“/”。
  • 我有这个:.WithOrigins("http://MY IP HERE/")
  • 它适用于我所有的 get 请求,但不适用于 post
  • @manta 不。你应该有 .WithOrigins("MY IP HERE") 。它不应该以 / 结尾。而且我不确定IP地址,从未尝试过。但也许它起作用了。
【解决方案2】:

我高度怀疑罪魁祸首在于: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSNotSupportingCredentials

不支持没有正确来源的凭据。

【讨论】:

  • 那么,有什么办法呢?我很想找到答案!!!
猜你喜欢
  • 2023-01-13
  • 2019-01-18
  • 2016-10-12
  • 1970-01-01
  • 2016-08-03
  • 2019-03-08
  • 2017-12-16
  • 2021-06-06
相关资源
最近更新 更多