.NET CORE 3 升级 CORS 和 Json(cycle) XMLHttpRequest 错误

.NET CORE 3 Upgrade CORS and Json(cycle) XMLHttpRequest Error

我的工作项目用 asp.net core 2.1 编写了很长时间,但是昨天,我被迫将它升级到 .net core 3.0 (由于 2.1 无法调用编写的 Dll已经在 3.0 中了)。

因此,许多功能已过时或已被删除。我修复了几乎所有问题,但 CORS 有一个问题。

像我之前的许多人一样,我使用:

app.UseCors(x => x
  .AllowAnyOrigin()
  .AllowAnyMethod()
  .AllowAnyHeader()
  .AllowCredentials());

Configure 函数中。并且 services.AddCors()ConfigureServices 函数中。

我可以很容易地通过设置 WithOrigins().SetIsOriginAllowed(_ => true) 而不是 AllowAnyOrigin() 来解决这个问题,后者不再适用于 AllowCredentials()

在那之后,我能够启动应用程序,我认为一切都很好,但直到现在我都遇到了问题,我不知道如何解决。

我有 DB 关系 N:N 和关系 table 来处理,这意味着我有 Admin 实体和 AdminProject list 属性,然后我有AdminProject 实体具有 Admin listProject list 属性,Project 实体再次具有 AdminProject list 属性。

当我列出某些管理员的项目时,我在控制器中 returning 这个 return Ok(projects),我只是在 AdminProject 实体上使用 getAll 然后只有 Select return 项目。

为此,我必须在 project/admin 中使用 [JsonIgnore] 来获取在创建 json 时不需要避免循环的属性。

话虽如此:现在在 .NET Core 3.0 和 CORS 设置中它不起作用

我收到一个错误: System.Text.Json.JsonException: A possible object cycle was detected which is not supported. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32.

在控制台中调试时,在 WEB 浏览器中出现错误 Access to XMLHttpRequest at 'http://localhost:5000/api/project/adminlist/1' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我想我尝试了几乎所有与 Cors 设置等有关的东西,但我不知道为什么现在会这样。我还尝试在 return 之前 JsonConvert.SerializeObject() ---> return Ok(JsonConvert.SerializeObject(projects)) 并且这是有效的,但我无法(在精神上)在每个控制器功能中都这样做。

请帮忙!非常感谢!

问题的发生是因为在 .NET Core 3 中它们稍微改变了 JSON 策略。 Json.Net 不再受支持,如果您想使用所有 Json 选项,您必须下载此 Nuget:Microsoft.AspNetCore.Mvc.NewtonsoftJson.

然后在 Startup.cs 文件 change/fix/add 行中添加 MVC(在 ConfigureServices 方法中。

所以:这是我所做的以及解决问题的方法:

services.AddMvc(option => option.EnableEndpointRouting = false)
                .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
                .AddNewtonsoftJson(opt => opt.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore);

希望对其他人有所帮助。 干杯!

.net core 3 中还发生了其他一些变化,现在您可以使用 addControllers 而不是 addMVC。所以您的代码可能如下所示:

services.AddControllers().AddNewtonsoftJson(x => x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);