【问题标题】:Asp Core 3.1 , Cors Not works for some api methodAsp Core 3.1,Cors 不适用于某些 api 方法
【发布时间】: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(); 之间。

标签: angular asp.net-core cors


【解决方案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 *

【讨论】:

    猜你喜欢
    • 2020-05-05
    • 2018-09-24
    • 2020-06-14
    • 2016-06-04
    • 2020-05-22
    • 2017-07-13
    • 2021-01-19
    • 1970-01-01
    • 2021-03-12
    相关资源
    最近更新 更多