You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React客户端向ASP.NET Core后端发送预检请求遭CORS策略拦截

解决React + ASP.NET Core跨域POST请求的CORS重定向问题

问题描述

我正在开发一个以React为客户端、ASP.NET Core为后端的简单应用,但尝试从React客户端向ASP.NET Core后端发送POST请求时,遇到以下CORS错误:

localhost/:1 Access to XMLHttpRequest at
'http://localhost:5094/api/records' from origin
'https://localhost:44477' has been blocked by CORS policy: Response to
preflight request doesn't pass access control check: Redirect is not
allowed for a preflight request.

后端Program.cs配置

using Microsoft.EntityFrameworkCore;
using Npgsql.EntityFrameworkCore.PostgreSQL;
using NET_REACT.Context;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddCors(o =>
{
    o.AddDefaultPolicy(
        builder =>
        {

          //you can configure your custom policy
            builder.WithOrigins("https://localhost:44477")
            .AllowAnyMethod()
            .AllowAnyHeader();
        });
});

builder.Services.AddControllersWithViews();

// Add services to the container.
builder.Services.AddControllersWithViews();

builder.Services.AddDbContext<MyDbContext>(
    o => o.UseNpgsql(builder.Configuration.GetConnectionString("MyPostgresConnection"))
);

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors();


app.MapControllerRoute(
    name: "default",
    pattern: "{controller}/{action=Index}/{id?}");

app.MapFallbackToFile("index.html");

app.Run();

React客户端App.js代码

import React, { useState } from 'react';
import axios from 'axios';

const App = () => {
  const [Name, setName] = useState('');
  const [Email, setEmail] = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();

    try {
      const response = await axios.post('http://localhost:5094/api/records', { Name, Email });
      console.log(response.data);
    } catch (error) {
      console.error('Error:', error.message);
    }
  };

  return (
    <div>
      <h1>Send POST Request</h1>
      <form onSubmit={handleSubmit}>
        <div>
          <label>Name: </label>
          <input type="text" value={Name} onChange={(e) => setName(e.target.value)} />
        </div>
        <div>
          <label>Email: </label>
          <input type="email" value={Email} onChange={(e) => setEmail(e.target.value)} />
        </div>
        <button type="submit">Submit</button>
      </form>
    </div>
  );
};

export default App;

解决方案

核心问题分析

错误提示里的**"Redirect is not allowed for a preflight request"**是关键:后端启用了app.UseHttpsRedirection()强制HTTP请求重定向到HTTPS,但前端请求用的是HTTP协议(http://localhost:5094),预检OPTIONS请求不允许被重定向,直接触发CORS拦截。

具体修复步骤

  1. 统一请求协议
    修改React客户端的Axios请求地址,把HTTP改为HTTPS:

    const response = await axios.post('https://localhost:5094/api/records', { Name, Email });
    

    注意:确认后端HTTPS端口为5094,可在launchSettings.json文件中查看配置

  2. 验证CORS中间件顺序
    确保app.UseCors()在app.UseRouting()之后、app.UseAuthorization()之前(如果有),当前代码的顺序是正确的,无需调整:

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();
    app.UseCors(); // 位置正确
    
  3. 可选:添加凭证支持(如果需要)
    如果请求需要携带Cookie或认证信息,在CORS配置中添加.AllowCredentials():

    builder.WithOrigins("https://localhost:44477")
           .AllowAnyMethod()
           .AllowAnyHeader()
           .AllowCredentials();
    
  4. 检查后端路由有效性
    确保/api/records的POST接口存在且没有额外的重定向逻辑,避免接口自身返回重定向响应。

额外排查点

  • 开发环境下可临时放宽CORS配置测试,但生产环境必须严格限制允许的源(不要使用通配符*搭配AllowCredentials,两者冲突)。
  • 确认Axios请求没有携带未被CORS配置允许的自定义请求头,AllowAnyHeader已覆盖所有需求。

内容的提问来源于stack exchange,提问作者Ah_bb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 17:55:59