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

.NET Core 2.2 API单一POST接口CORS策略错误求助

解决.NET Core 2.2 API新增POST方法后出现的CORS跨域错误

看起来你遇到的问题很典型——之前配置好的CORS策略突然失效,其实大概率不是CORS配置本身的问题,而是请求本身的错误或者后端代码的异常导致浏览器误报了CORS错误。我帮你一步步排查和修复:

1. 先修复前端请求的参数传递问题

你的后端POST方法明确需要rows和cols两个参数,但前端的$.post调用完全没有传递这两个值!这会直接导致后端返回400 Bad Request错误,而浏览器经常会把这类非2xx状态码的错误和CORS问题混淆显示,让你误以为是跨域配置出了问题。

修改前端代码,把参数正确传递给后端:

const fnAddNewSlots = () => {
    let rows = $("#ntbRows").val();
    let cols = $("#ntbCols").val();
    // 新增参数传递部分
    $.post("url", { rows: rows, cols: cols }, (data) => {
        toastr.success("New slots added successfully");
    }).fail((e) => {
        toastr.error("Error trying to add new slots");
        console.log(e);
    });
}

2. 修复后端POST方法的潜在异常

你的POST方法里有两个严重的隐患,一旦触发会抛出未处理的异常,导致返回500错误,同样会被浏览器关联到CORS问题上:

  • 如果RackSlots表为空,Last()方法会直接抛出InvalidOperationException(序列无元素)
  • 即使表不为空,后续的循环逻辑也可能因为边界计算错误导致异常

修改后端代码,添加空值检查和异常处理:

[HttpPost]
public async Task<IActionResult> PostRackSections(int rows, int cols)
{
    var lastRackSlot = _context.RackSlots.OrderBy(rs => rs.Row).ThenBy(rs => rs.Column).LastOrDefault();
    
    // 处理表为空的边界情况
    if (lastRackSlot == null)
    {
        for (byte i = (byte)'A'; i <= (byte)'A' + rows - 1; i++)
        {
            for (int j = 1; j <= cols; j++)
            {
                _context.RackSlots.Add(new RackSlots { Row = Encoding.ASCII.GetString(new byte[] { i }), Column = j, Enabled = true });
            }
        }
    }
    else
    {
        byte startRow = (byte)(lastRackSlot.Row.ElementAt(0) + 1);
        // 修正循环边界,避免超出预期范围
        for (byte i = startRow; i <= startRow + rows - 1; i++)
        {
            for (int j = 1; j <= lastRackSlot.Column; j++)
            {
                _context.RackSlots.Add(new RackSlots { Row = Encoding.ASCII.GetString(new byte[] { i }), Column = j, Enabled = true });
            }
        }
        
        int startCol = lastRackSlot.Column + 1;
        for (int j = startCol; j <= startCol + cols - 1; j++)
        {
            for (byte i = (byte)'A'; i <= lastRackSlot.Row.ElementAt(0); i++)
            {
                _context.RackSlots.Add(new RackSlots { Row = Encoding.ASCII.GetString(new byte[] { i }), Column = j, Enabled = true });
            }
        }
    }
    
    try
    {
        await _context.SaveChangesAsync();
        return NoContent();
    }
    catch (DbUpdateException ex)
    {
        // 建议添加日志记录
        return StatusCode(StatusCodes.Status500InternalServerError, "Failed to save slot data");
    }
    catch (Exception ex)
    {
        // 捕获其他未知异常,避免直接抛出导致无CORS头的响应
        return StatusCode(StatusCodes.Status500InternalServerError, "An unexpected error occurred");
    }
}

3. 确认CORS配置的细节

你的Startup里的CORS配置顺序是正确的(UseCors在UseMvc之前),但有个细节需要注意:

  • 如果你的前端请求不需要携带凭证(比如Cookie、HTTP认证信息),当前的AllowAnyOrigin()配置没问题
  • 如果需要携带凭证,AllowAnyOrigin()和AllowCredentials()不能同时使用,必须指定具体的Origin,比如:
    builder.WithOrigins("http://localhost")
           .AllowAnyMethod()
           .AllowAnyHeader()
           .AllowCredentials();
    

4. 验证预检请求(可选)

如果你的请求包含非简单请求的头信息(比如自定义Header),浏览器会先发OPTIONS预检请求。可以通过浏览器开发者工具的Network标签查看:

  • 是否有OPTIONS请求发送到后端
  • 响应头中是否包含Access-Control-Allow-Origin

如果OPTIONS请求失败,检查是否有其他中间件(比如权限验证)拦截了OPTIONS请求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 06:52:33