Categories
asp.net-core asp.net-core-3.0 cors json xmlhttprequest

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

I had my working project written in asp.net core 2.1 for a long time, but yesterday, I was forced to upgrade it to .net core 3.0 (due to 2.1 cannot call Dll’ s which are written in 3.0 already).

With that, a lot of functions were obsolete or already removed. I fixed almost all of it, but one problem with CORS.

Like many people before me, I used:

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

in Configure function. And services.AddCors() in ConfigureServices function.

I was able to fixed this quite easily with setting WithOrigins() or .SetIsOriginAllowed(_ => true) instead of AllowAnyOrigin() which does not work anymore with AllowCredentials().

After that, I was able to start the application and I thought everything is fine, but then I get stuck until now with problem I do not know, how to fix.

I have DB relation N:N and relation table which handle that, that means I have Admin entity with AdminProject list property, then I have AdminProject entity with Admin list and Project list properties and Project entity with AdminProject list property once again.

When I am listing my projects of certain admin, I am returning in Controller this return Ok(projects), where I just use getAll on AdminProject entity and then with Select return only project.

For that, I have to use[JsonIgnore] in project/admin for properties which I do not need to avoid cycling when creating json.

With that said: NOW IN .NET CORE 3.0 AND CORS SETTINGS IT DOES NOT WORK.

I am getting an error:
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.

when debugging in console and error 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. in WEB browser

I think I tried almost everything with Cors settings etc and I do not know why is this happening now. I also tried to JsonConvert.SerializeObject() before return it —> return Ok(JsonConvert.SerializeObject(projects)) and this is working, but I am not able (mentally) to do this in every single controllers functions.

Please help! Thanks a lot!