Asp Core 3.1,Cors 不适用于某些 api 方法

Posted

技术标签:

【中文标题】Asp Core 3.1,Cors 不适用于某些 api 方法【英文标题】:Asp Core 3.1 , Cors Not works for some api method 【发布时间】:2021-09-19 02:00:53 【问题描述】:

我在 asp core 3.1 中使用此代码为我的 web api 禁用了 cors:

app.UseCors(x => x
    .AllowAnyMethod()
    .AllowAnyHeader()
    .SetIsOriginAllowed(origin => true) // allow any origin
    .AllowCredentials()); // allow credentials

我通过 Angular 9 调用我的 api 方法,问题是当我调用某些方法时,我会遇到这样的 Cors 错误:

Access to XMLHttpRequest at 'https://porsapp-api.ketabist.ir/api/v1/exam/get_user_next_exams' from origin 'https://porsapp-panel.ketabist.ir' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我有两个 api 方法,它们在同一个控制器中写成彼此相同:

[HttpGet("get_user_previous_exams")]
[ProducesResponseType(200, Type = typeof(UserPreviousExamsResponse))]
public async Task<IActionResult> GetUserPreviousExams(int page_num, int page_size, CancellationToken cancellationToken)

    var mobile = User.TryGetUsername();
    var userId = User.GetUserId();

    if (page_num == 0)
    
        page_num = 1;
    

    if (page_size == 0)
    
        page_size = 20;
    

    var exams = await _examStudentsService.GetPreviousStudentExams(userId, mobile, page_num, page_size);
    if (exams == null || exams.CountAll == 0)
    
        return Ok();
    

    var res = exams.Items.Select(x => _responseMapper.ToUserPreviousExamResponse(x));

    return Ok(new UserPreviousExamsResponse
    
        items = res.ToList(),
        count_all = exams.CountAll,
    );

调用上面的代码是好的并返回我的结果,但是下面的方法返回 Cors 错误!

[HttpGet("get_user_next_exams")]
[ProducesResponseType(200, Type = typeof(List<UserNextExamResponse>))]
public async Task<IActionResult> GetUserNextExams(CancellationToken cancellationToken)

    try
    
        var mobile = User.TryGetUsername();
        var userId = User.GetUserId();

        var exams = await _examStudentsService.GetFutureStudentExams(userId, mobile);
        if (exams == null || exams.Count == 0)
        
            return Ok(new List<UserNextExamResponse>());
        

        var res = exams.Select(x => _responseMapper.ToUserNextExamResponse(x, _settingsReader));
        return Ok(res.ToList());
    
    catch(Exception ex)
    
        return BadRequest(ex);
    


请帮我解决这个错误

【问题讨论】:

检查以确保您没有遇到异常,在后端设置断点并查看它是否被命中。 IIS 错误页面没有 CORS 标头。这并不是说它不匹配,而是说标题不存在。还要检查网络选项卡并确保您的获取参数存在,然后将 [FromQuery] 放在它们上面。 你在启动时把 cors 配置放在哪里?你需要把它放在app.UseRouting();app.UseAuthorization(); 之间。 【参考方案1】:

1.尝试确保您的cors配置在正确的位置:

app.UseRouting();
app.UseCors(x => x
    .AllowAnyMethod()
    .AllowAnyHeader()
    .SetIsOriginAllowed(origin => true) // allow any origin
    .AllowCredentials());
app.UseAuthorization();

2.如果你在IIS中托管你的项目,你需要在IIS中设置响应头Allow-Access-Control-Origin *

【讨论】:

以上是关于Asp Core 3.1,Cors 不适用于某些 api 方法的主要内容,如果未能解决你的问题,请参考以下文章

CORS 不适用于从 Ajax 到 ASP.NET Core Web API 的调用

Set-cookie 不适用于 Dot net Core 3.1 中的跨站点请求/响应和 React 设置同站点 cookie 和/或 CORS 问题

JWT 不记名令牌不适用于 ASP.Net Core 3.1 + Identity Server 4

在 ASP.NET Core 3.1 中处理多环境的 CORS 策略

如何在 asp.net core 3.1 中为每种类型的请求启用 Cors

Angular 8 使用 ASP NET Core 3.1 Web Api 时出现 CORS 策略问题