json - 使用大量搜索条件从 Angular 调用 API HttpGet Action 会引发 CORS 策略错误
问题描述
我有一个 Core 2.2 Web API 项目作为 Angular 前端的后端。在一个屏幕上,我允许用户从数据网格中选择要处理的 x 条记录。在处理记录之前,我需要通过将 3 个字段(智能密钥)的列表传递给我的 API 来检查数据库以查看记录是否存在于另一个表中。我将此列表放入对象数组中,对该对象执行 Json.stringify 并将其作为 Get 请求发送到我的 API。只要我选择 1-3 条记录,它就可以正常工作。一旦我选择 4 条或更多记录,我就会得到“从源 ' http://localhost:4200 ' 对 XMLHttpRequest 的访问已被 CORS 策略阻止:没有 'Access-Control-Allow-Origin' 标头出现在请求的资源上。”
我的 Cors 政策表明它应该让任何事情通过,我也对为什么 1-3 条记录可以正常工作感到困惑。
在我的 startup.cs -> ConfigureServices 方法中,我定义了 Cors 策略,如下所示:
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.WithOrigins("http://localhost:4200")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
在我的 Angular 服务中,我进行了这个按数组序列化的调用(apiUrl 是我调用 API 的 URL:https://localhost/api/controller)
getRecordsByIntelligentKey(intelligentKey: IntelligentKey[]): Observable<Record[]>{
const jsonObject = JSON.stringify(intelligentKey);
const url = `${apiUrl}/${jsonObject}`;
return this.http.get<Record[]>(url).pipe(
tap(_ => console.log('fetching records based on intelligent key')),
catchError(this.handleError('getRecordsByIntelligentKey', []))
);
}
在我的控制器 GET 操作中,我反序列化了我的字符串。我的意思是我想传递一个对象,但我认为我需要为此做一个 POST。
[HttpGet("{jsonObject}")]
public ActionResult<List<Commission>> GetByCustomerAndTerritoryManager(string jsonObject)
{
try
{
var intelligentKey = JsonConvert
.DeserializeObject<List<ThreeFields>>(jsonObject);
return _repo.GetRecordsByIntelligentKey(intelligentKey);
}
catch (Exception ex)
{
_logger.Error(ex, "Error retrieving records.");
throw;
}
}
现在我的问题是用户可以选择 1000 条记录。当我选择超过 1000 条记录时,我只得到 ERR_CONNECTION_RESET 可能是因为查询字符串太长了。
我在想我需要一个对象,但我研究过的所有东西似乎都建议不要使用 GET 来执行此操作,而是使用 POST 请求。问题是,它是一个安静的 API,我已经在处理部分使用 POST 请求。我想我可以使用 PUT 或 DELETE 但感觉不对。我将在发布此问题后立即连接 PUT 以查看它是否有效,但最终我想为此找到正确的解决方案。
更新:即使选择了超过 1000 条记录,PUT 方法也能正常工作,所以我想这将是我现在的临时解决方案。我仍然觉得有代码气味并且很想使用 GET 但至少这让我可以继续。
解决方案
推荐阅读
- python - SQLite WHERE 语句为空
- javascript - Eclipse JQuery 不适用于我的简单 Hello World 程序
- azure-functions - 有没有办法告诉天蓝色函数的最后发布日期?
- android - 后端内部错误:代码生成期间出现异常
- android - 从 url 加载图像的高效快捷方式
- c - 为什么我不断收到多重定义错误?
- angular - 理解嵌套的 observables 的行为
- java - 空值检查与 findFragmentByTag 中的 Objects.requireNonNull
- python - iGraph 垂直布局而不是水平布局
- java - Java中的变量是如何被调用的,这些变量被设置一次但不再设置并且不是最终的?