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



我已经在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);
}
}

请帮我修复这个错误

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 *

最新更新