Самостоятельная ссылка на ошибку .NET core 3.0 newtonsoft - PullRequest
0 голосов
/ 09 ноября 2019

Я получаю эту ошибку, когда пытаюсь выполнить какой-то запрос

Обнаружен самоссылочный цикл для свойства «Компания» с типом «ApplicationCore.Entities.IntekManager.Company». Путь 'Departments [0]'.

my program.cs

using System.IO;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;

namespace Service
{
    public class Program
    {
        public static string ProgramName = "TabletMenu";

        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args)
        {
            return WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .UseKestrel(opt =>
                {
                    opt.Limits.MaxRequestBodySize = long.MaxValue;
                })
                .UseUrls("http://*:5001")
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .Build();
        }
    }
}

my startup.cs

using ApplicationCore.Interfaces;
using Infrastructure.Data;
using Infrastructure.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using System.Web.Http;

namespace Service
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; set; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(option => option.EnableEndpointRouting = false)
                .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
                .AddNewtonsoftJson(opt => opt.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore);

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

            services.AddDbContext<ApplicationManagerContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("ManagerConnection"),
             opt => opt.UseRowNumberForPaging()));

            services.AddScoped(typeof(IAsyncRepository<>), typeof(EfRepository<>));
            services.AddScoped(typeof(IDapperRepository<>), typeof(BaseDapperRepository<>));
            services.AddTransient(typeof(ProductService));
            services.AddTransient(typeof(TokenService));
            services.AddTransient(typeof(BranchService));
            services.AddTransient(typeof(ProductGroupService));
            services.AddTransient(typeof(FinishedProductService));
            services.AddTransient(typeof(TabletParameterService));
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

            services.AddTransient(s => s.GetService<IHttpContextAccessor>().HttpContext.User);
            services.AddTransient(typeof(ConnectionService));

            services.AddMemoryCache();

            services.AddResponseCompression();

            services.AddCors();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
            Configuration = builder.Build();

            app.UseStaticFiles();

            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            });

            app.UseAuthentication();

            app.UseCors(
                options => options
                    .AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
            );

            app.UseResponseCompression();

            app.UseMvc();
        }


    }
}

Я пробовал эти коды, но не работалпо-прежнему получаю ошибку

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

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

что мне делать?

код контроллера таков:

using ApplicationCore.Entities.IntekManager;
using ApplicationCore.Interfaces;
using Infrastructure.Services;
using Microsoft.AspNetCore.Mvc;
using Service.ViewModels.Account;
using System;
using System.Threading.Tasks;
using Web.Controllers;

namespace Service.Controllers.AccountController
{
    public class AccountController : BaseApiController
    {
        public IAsyncRepository<Company> _companyRepository;
        public IAsyncRepository<Department> _departmentRepository;
        public TokenService _tokenService;

        public AccountController(IAsyncRepository<Company> companyRepository,
            IAsyncRepository<Department> departmentRepository,
            TokenService tokenService)
        {
            _companyRepository = companyRepository;
            _tokenService = tokenService;
            _departmentRepository = departmentRepository;
        }

        [HttpPost]
        public async Task<IActionResult> LoginTablet([FromBody] LoginViewModel model)
        {
            try
            {
                var department = await _departmentRepository.FindFilterIncludeAsync(x => x.UserName == model.UserName, x => x.Company);

                if (department == null) return BadRequestResult("Sistemde Böyle Bir Kullanıcı Bulunamadı");

                if (department.Password != model.Password) return BadRequestResult("Şifre Yanlış");

                if (department.LicenceLastTime < DateTime.Now) return BadRequestResult("Lisans Süresi Dolmuş");

                if (!department.Active) return BadRequestResult("Sistem Aktif Değil");

                department.DateResult = department.LicenceLastTime.Day + "/" + department.LicenceLastTime.Month + "/" + department.LicenceLastTime.Year;
                department.RestDay = Math.Round((department.LicenceLastTime - DateTime.Now).TotalDays).ToString() + " GÜN";

                department.Company.CurrentDepartmentName = department.Name;

                department.CompanyName = department.Company.CompanyName;

                return OkResult(new
                {
                    department,
                    token = _tokenService.GetJWTToken(department.Company)
                });
            }
            catch (Exception ex)
            {
                return BadRequestResult("Beklenmedik Bir Hata Meydana Geldii : " + ex.Message);
            }
        }


    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...