c# - 错误 "{"stateMachine": {"<>1__state":-2 ,"<>t__builder":{"when run project netcore

标签 c# asp.net-core .net-core automapper

当我运行项目 netcore 时,我收到一条消息 {"stateMachine":{"<>1__state":-1,"<>t__builder":{ 我不知道如何解决这个问题。我在命令行中看到错误

Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1] An unhandled exception has occurred while executing the request. Newtonsoft.Json.JsonSerializationException: Self referencing loop detected for property 'task' with type 'System.Runtime.CompilerServices.AsyncTaskMethodBuilder`





Microsoft.AspNetCore.Server.Kestrel[13] Connection id "0HLFMHMJ7MBQN", Request id "0HLFMHMJ7MBQN:00000001": An unhandled exception was thrown by the application. Newtonsoft.Json.JsonSerializationException: Self referencing loop detected for property 'task' with type 'System.Runtime.CompilerServices.AsyncTaskMethodBuilder`



这是文件 Startup.cs
 public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.AddDbContext<AppDbContext>(options =>
               options.UseSqlServer(Configuration.GetConnectionString("AppDbConnection"),
                   b => b.MigrationsAssembly("liyobe.Data")));

        services.AddIdentity<AppUser, AppRole>()
            .AddEntityFrameworkStores<AppDbContext>()
            .AddDefaultTokenProviders();
        // Configure Identity
        services.Configure<IdentityOptions>(options =>
        {
            // Password settings
            options.Password.RequireDigit = true;
            options.Password.RequiredLength = 6;
            options.Password.RequireNonAlphanumeric = false;
            options.Password.RequireUppercase = false;
            options.Password.RequireLowercase = false;

            // Lockout settings
            options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
            options.Lockout.MaxFailedAccessAttempts = 10;

            // User settings
            options.User.RequireUniqueEmail = true;
        });

        services.AddAutoMapper();

        // Add application services.
        services.AddScoped<UserManager<AppUser>, UserManager<AppUser>>();
        services.AddScoped<RoleManager<AppRole>, RoleManager<AppRole>>();

        //CreateMapper(services, Configuration);
        //services.AddSingleton(Mapper.Configuration);
        services.AddScoped<IMapper>(sp => new Mapper(sp.GetRequiredService<AutoMapper.IConfigurationProvider>(), sp.GetService));

        services.AddTransient(typeof(IUnitOfWork), typeof(EFUnitOfWork));
        services.AddTransient(typeof(IAsyncRepository<,>), typeof(EFRepository<,>));
        services.AddTransient<IFunctionService, FunctionService>();
        services.AddTransient<DbInitializer>();
        //services.AddMvc();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/error");
        }
        //app.UseStaticFiles();
        //app.UseHttpsRedirection();
        app.UseMvc();
    }

这是我的文件 ValuesController
[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    IFunctionService _functionService;
    public ValuesController(IFunctionService functionService)
    {
        _functionService = functionService;
    }
    // GET api/values
    [HttpGet]
    public async  Task<IActionResult> Get()
    {
        try
        {
            var data = _functionService.GetAll("");
            return Ok(data);
        }
        catch (Exception ex)
        {
            throw new Exception();
        }
    }

这是 FunctionService 类中的函数 getAll
public async Task<List<FunctionViewModel>> GetAll(string functionId)
    {
        var query = await _functionRepository.ListAllAsync();
        var result = _mapper.Map<List<Function>, List<FunctionViewModel>>(query);
        return result;
    }

这是类功能
public class FunctionViewModel
{
    public string Id { get; set; }

    [Required]
    [StringLength(128)]
    public string Name { set; get; }

    [Required]
    [StringLength(250)]
    public string URL { set; get; }

    [StringLength(128)]
    public string ParentId { set; get; }

    public string IconCss { get; set; }
    public int SortOrder { set; get; }
    public bool Status { set; get; }
}

这是类功能
[Table("Functions")]
public class Function : BaseEntity<string>, ISwitchable, ISortable
{
    public Function()
    {

    }
    public Function(string name, string url, string parentId, string iconCss, int sortOrder)
    {
        this.Name = name;
        this.URL = url;
        this.ParentId = parentId;
        this.IconCss = iconCss;
        this.SortOrder = sortOrder;
    }
    [Required]
    [StringLength(128)]
    public string Name { set; get; }

    [Required]
    [StringLength(250)]
    public string URL { set; get; }


    [StringLength(128)]
    public string ParentId { set; get; }

    public string IconCss { get; set; }
    public int SortOrder { set; get; }
    public bool Status { set; get; }
}

我看到在 FunctionService 中返回数据时发生错误。但我不知道如何解决这个问题。

最佳答案

 // GET api/values
[HttpGet]
public async  Task<IActionResult> Get()
{
    try
    {
        var data = await _functionService.GetAll("");
        return Ok(data);
    }
    catch (Exception ex)
    {
        throw new Exception();
    }
}

关于c# - 错误 "{"stateMachine": {"<>1__state":-2 ,"<>t__builder":{"when run project netcore,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51604749/

相关文章:

c# - 为什么带有多个分号的代码可以编译?

c# - Entity Framework 6.1.3 : InvalidOperationException after a few days of running

c# - 维护排序顺序的集合 C#

c# - 在 .Net Core 中禁用模型绑定(bind)器

C# listview imagelist 快速添加多个项目

azure - 未下载用于 Azure 构建的 Nuget 包

asp.net - 将具有策略的授权应用于 asp.net core 中命名空间内的所有 Controller

c# - Microsoft.Extensions.Configuration 究竟是如何依赖 ASP.NET Core 的?

c# - 如何在 EF Core 2 中为 .ThenInclude 编写 Repository 方法

c# - 如何正确测试库的 .NET Standard 和 Core 版本?