【问题标题】:Error "{"stateMachine":{"<>1__state":-2,"<>t__builder":{" when run project netcore运行项目 net core 时出现错误 "{"state Machine":{"<>1__state":-2,"<>t__builder":{"
【发布时间】:2018-07-31 02:45:33
【问题描述】:

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

Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1] 执行请求时发生未处理的异常。 Newtonsoft.Json.JsonSerializationException:检测到类型为“System.Runtime.CompilerServices.AsyncTaskMethodBuilder”的属性“任务”的自引用循环

Microsoft.AspNetCore.Server.Kestrel[13] 连接 ID“0HLFMHMJ7MBQN”,请求 ID“0HLFMHMJ7MBQN:00000001”:应用程序引发了未处理的异常。 Newtonsoft.Json.JsonSerializationException:检测到类型为“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 中返回数据时发生错误。但我不知道如何解决这个问题。

【问题讨论】:

  • 你不是awaiting _functionService.GetAll("")
  • 好的。谢谢。我解决了。
  • 等待是关键,谢谢johanp
  • @ltiendat95 我也遇到了同样的问题,你能解释一下你是怎么解决的吗?
  • @JohanP 您可以添加您的评论作为答案吗?所以我们可以这样标记。 (是的 - 这是罪魁祸首,你的评论在 3 分钟内解决了我的错误)

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


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

【讨论】:

  • 虽然此代码可能会为问题提供解决方案,但最好添加有关其工作原理/方式的上下文。这可以帮助未来的用户学习并最终将这些知识应用到他们自己的代码中。解释代码时,您也可能会得到用户的积极反馈/赞成。
  • 嗨@Muhammad。感谢您的贡献!您能否解释一下代码的作用以及为什么它解决了这个问题?不幸的是,这并不明显。
猜你喜欢
  • 2021-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-19
  • 2020-11-16
  • 2018-05-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多