如何避免循环引用ASP.NET Core MVC [HttpPost("add-recipe")] Web API [英] How to avoid the circular referencing asp.net core mvc [HttpPost("add-recipe")] web api
问题描述
我的项目是带有食谱的应用程序(烹饪).NET Core 5.0
My project is Application with Recipes (cooking) .NET Core 5.0
我在添加新配方(HttpPost)Web API时遇到问题
And i have problem with adding a new recipe (HttpPost) web api
关于邮递员,我的答复是:
On postman my response is:
检测到可能的对象周期.这可能是由于循环引起的,或者如果对象深度大于允许的最大深度32.请考虑对JsonSerializerOptions使用ReferenceHandler.Preserve支持循环."
当我创建新食谱时,应使用recipeToCreateDto而不是包含所有属性(循环引用)的食谱
When i'm creating a new recipe it should use recipeToCreateDto instead of Recipe - which contains all properties (circular referencing)
您能帮我如何使其正常运行吗?如何映射等.
Could you help me how to make it working properly. How to map etc.
https://i.postimg.cc/Mphv7zRH/screen.png <-屏幕在这里
https://i.postimg.cc/Mphv7zRH/screen.png <- screen here
我正在使用AutoMapper映射类和存储库模式.
I'm using AutoMapper for mapping classes and Repository Pattern.
public class AppUser
{
public int Id { get; set; }
public string UserName { get; set; }
public ICollection<Recipe> Recipes {get; set;}
}
}
用户有很多食谱.
public class Recipe
{
public int Id { get; set; }
public string Name { get; set; }
public AppUser AppUser { get; set; }
public int AppUserId { get; set; }
}
数据传输对象
public class RecipeForCreateDto
{
[Required]
[StringLength(50, MinimumLength = 3, ErrorMessage = "You must specify name between 3 and 50 characters")]
public string Name { get; set; }
public int AppUserId { get; set; }
public int AuthorId { get; set; }
}
在我的AutoMapperProfiles.cs中
In my AutoMapperProfiles.cs
public class AutoMapperProfiles : Profile
{
public AutoMapperProfiles()
{
CreateMap<RecipeForCreateDto, Recipe>();
}
配方界面
public interface IRecipeRepository
{
Task<Recipe> AddNewRecipe(Recipe recipe);
}
public class RecipeRepository : IRecipeRepository
{
private readonly DataContext _context;
private readonly IMapper _autoMapper;
public RecipeRepository(DataContext context, IMapper autoMapper)
{
_autoMapper = autoMapper;
_context = context;
}
public async Task<Recipe> AddNewRecipe(Recipe recipe)
{
await _context.Recipes.AddAsync(recipe);
await _context.SaveChangesAsync();
return recipe;
}
}
用户控制器:
User.GetUsername()是获取用户名的静态方法.
User.GetUsername() is static method that is getting User's username.
[HttpPost("add-recipe")]
public async Task<ActionResult> AddNewRecipe(RecipeForCreateDto recipeForCreateDto)
{
var userFromRepo = await _userRepository.GetUserByUsernameAsync(User.GetUsername());
recipeForCreateDto.Name = recipeForCreateDto.Name.ToLower();
if (await _recipeRepository.RecipeExists(recipeForCreateDto.Name))
return BadRequest("Recipe with that name already exists!");
var recipeToCreate = _autoMapper.Map<Recipe>(recipeForCreateDto);
recipeToCreate.AppUserId = userFromRepo.Id;
var createdRecipe = await _recipeRepository.AddNewRecipe(recipeToCreate); // here is problem
var recipeToReturn = _autoMapper.Map<RecipeForDetailDto>(createdRecipe);
return CreatedAtRoute("GetRecipe", new { controller = "Recipes", id = createdRecipe.Id }, recipeToReturn);
}
推荐答案
检测到可能的对象周期.这可能是由于循环或对象深度大于最大允许深度之32.考虑在以下位置使用ReferenceHandler.PreserveJsonSerializerOptions以支持周期."
"A possible object cycle was detected. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32. Consider using ReferenceHandler.Preserve on JsonSerializerOptions to support cycles."
对于此问题,您可以在startup.cs ConfigureServices
方法中添加以下代码:
For this issue , you can add the following code in startup.cs ConfigureServices
method:
services.AddControllersWithViews()
.AddNewtonsoftJson(options =>
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);
这篇关于如何避免循环引用ASP.NET Core MVC [HttpPost("add-recipe")] Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!