Open Closed

getting issue while adding new controller for a new entity Repository #7523


User avatar
0
Vilasini created
  • ABP Framework version: 7.0
  • UI Type: MVC Razor pages
  • Database System: EF Core (SQL Server)
  • Tiered (for MVC) or Auth Server Separated (for Angular): no
  • Exception message and full stack trace:
  • { "error": { "code": null, "message": "An internal error occurred during your request!", "details": null, "data": { "ActivatorChain": "Volo.Abp.Identity.IdentityAuthenticationPoliciesController -> Volo.Abp.Identity.AuthPolicy.TenantPolicyAppService" }, "validationErrors": null } }
  • Steps to reproduce the issue:
  • added a new controller in Identity module when i'm trying to test getting this issue help me out
  • PFB controller created
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.Identity.AuthPolicy;

namespace Volo.Abp.Identity
{
    [RemoteService(Name = IdentityProRemoteServiceConsts.RemoteServiceName)]
    [Area(IdentityProRemoteServiceConsts.ModuleName)]
    [ControllerName("AuthenticationPolicies")]
    [Route("api/identity/authentication-policies")]
    public class IdentityAuthenticationPoliciesController: AbpControllerBase
    {
        private readonly ITenantPolicyAppService _tenantPolicyAppService;
        private readonly IAuthenticationPolicyAppService _authenticationPolicyAppService;
        public IdentityAuthenticationPoliciesController(ITenantPolicyAppService tenantPolicyAppService, 
            IAuthenticationPolicyAppService authenticationPolicyAppService)
        {
            _tenantPolicyAppService = tenantPolicyAppService;
            _authenticationPolicyAppService = authenticationPolicyAppService;
        }

        [HttpGet]
        [Route("authentication-policies-list")]
        public virtual Task<PagedResultDto<AuthPolicyResponseDto>> GetAllAuthenticationPoliciesListAsync(GetAllRequestDto input)
        {
            return _authenticationPolicyAppService.GetAllAuthenticationPoliciesListAsync(input);
        }
    }
}

14 Answer(s)
  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    Please share full error logs and code of TenantPolicyAppService and AuthenticationPolicyAppService

    Thanks.

  • User Avatar
    0
    Vilasini created

    Hi,

    Here i am providing the code and error log

    Code: IAuthenticationPolicyAppService interface :

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Volo.Abp.Application.Dtos;
    using Volo.Abp.Application.Services;
    
    namespace Volo.Abp.Identity.AuthPolicy
    {
        public interface IAuthenticationPolicyAppService : IApplicationService
        {
            Task<PagedResultDto<AuthPolicyResponseDto>> GetAllAuthenticationPoliciesListAsync(GetAllRequestDto input);
        }
    }
    
    AuthenticationPolicyAppService class :
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Volo.Abp.Application.Dtos;
    using Volo.Abp.Application.Services;
    using Volo.Abp.Domain.Repositories;
    using System.Linq.Dynamic.Core;
    
    
    namespace Volo.Abp.Identity.AuthPolicy
    {
        //[Authorize(IdentityPermissions.AuthenticationPolicy.Default)]
        public class AuthenticationPolicyAppService : ApplicationService, IAuthenticationPolicyAppService
        {
            private readonly IAuthenticationPolicyRepository _authenticationPolicyRepository;
            private readonly ITenantAuthenticationsRepository _tenantAuthenticationsRepository;
            private readonly IIdentityUserRepository _identityUserRepository;
            private readonly IOrganizationUnitRepository _organizationUnitRepository;
            private readonly IRepository<IdentityUserOrganizationUnit> _IdentityUserOrganizationUnitRepository;
    
            public AuthenticationPolicyAppService(IAuthenticationPolicyRepository authenticationPolicyRepository, ITenantAuthenticationsRepository tenantAuthenticationsRepository,
                IIdentityUserRepository identityUserRepository, IOrganizationUnitRepository organizationUnitRepository,
                IRepository<IdentityUserOrganizationUnit> IdentityUserOrganizationUnitRepository)
            {
                _authenticationPolicyRepository = authenticationPolicyRepository;
                _identityUserRepository = identityUserRepository;
                _organizationUnitRepository = organizationUnitRepository;
                _IdentityUserOrganizationUnitRepository = IdentityUserOrganizationUnitRepository;
                _tenantAuthenticationsRepository = tenantAuthenticationsRepository;
            }
    
    
            //For Authentication policies...
            public async Task<PagedResultDto<AuthPolicyResponseDto>> GetAllAuthenticationPoliciesListAsync(GetAllRequestDto input)
            {
                var totalCount = await _authenticationPolicyRepository.GetCountAsync(input.Filter, input.PolicyName);
                var items = await _authenticationPolicyRepository.GetListAsync(input.Filter, input.PolicyName, input.Sorting, input.MaxResultCount, input.SkipCount);
    
                var policiesList = items.Select(x => new AuthPolicyResponseDto
                {
                    Name = x.Name,
                    IdentityType = x.IdentityType.ToString(),
                    Identity = GetUserOrGroupName(x.IdentityType, x.Identity).ToString(),
                    MFALevels = x.MFALevels,
                    Authentications = x.Authentications,
                    AlternateAuthentications = x.AlternateAuthentications
    
                }).ToList();
                return new PagedResultDto<AuthPolicyResponseDto>
                {
                    TotalCount = totalCount,
                    Items = policiesList
                };
            }
        }
    }
    
    //ITenantPolicyAppservice interface...
    
    using System.Threading.Tasks;
    using Volo.Abp.Application.Services;
    
    namespace Volo.Abp.Identity.AuthPolicy
    {
        public  interface ITenantPolicyAppService : IApplicationService
        {
            Task<TenantPolicyDto> GetTenantAuthenticationPolicyAsync();
    
            Task<BaseResponseDto> UpdateTenantAuthenticationPolicy(TenantPolicyDto input);
    
        }
    }
    

    Implimentation...

    using System.Linq;
    using System.Threading.Tasks;
    using Volo.Abp.Application.Services;
    
    namespace Volo.Abp.Identity.AuthPolicy
    {
        public class TenantPolicyAppService : ApplicationService, ITenantPolicyAppService
        {
            public readonly ITenantAuthenticationsRepository _tenantAuthenticationsRepository;
    
            public TenantPolicyAppService (ITenantAuthenticationsRepository tenantAuthenticationsRepository)
            {
                _tenantAuthenticationsRepository = tenantAuthenticationsRepository;
            }
            
            public async Task<TenantPolicyDto> GetTenantAuthenticationPolicyAsync()
            {
                using (CurrentTenant.Change(this.CurrentTenant?.Id))
                {
                    var tenantauthpolicy =  _tenantAuthenticationsRepository.GetListAsync().Result.FirstOrDefault();
                    return new TenantPolicyDto
                    { 
                        MFA = tenantauthpolicy.MFA,
                        PrimaryAuthentication = tenantauthpolicy.PrimaryAuthentication,
                        SecondaryAuthentication =tenantauthpolicy.SecondaryAuthentication,
                        AlternateAuthentications =tenantauthpolicy.AlternateAuthentications,
                        EnableAdaptiveAuthentication =tenantauthpolicy.EnableAdaptiveAuthentication
    
                    };
                }
               
               
            }
    
            public async Task<BaseResponseDto> UpdateTenantAuthenticationPolicy(TenantPolicyDto input)
            {
               
                using (CurrentTenant.Change(this.CurrentTenant?.Id))
                {
                    var updatetenantauthpolicy = _tenantAuthenticationsRepository.GetListAsync().Result.FirstOrDefault();
                    if (updatetenantauthpolicy != null)
                    {
                        updatetenantauthpolicy.MFA = input.MFA;
                        updatetenantauthpolicy.PrimaryAuthentication = input.PrimaryAuthentication;
                        updatetenantauthpolicy.SecondaryAuthentication = input.SecondaryAuthentication;
                        updatetenantauthpolicy.AlternateAuthentications = input.AlternateAuthentications;
                        updatetenantauthpolicy.EnableAdaptiveAuthentication = input.EnableAdaptiveAuthentication;
                         await _tenantAuthenticationsRepository.UpdateAsync(updatetenantauthpolicy,true);
                    }
                    else
                    {
                        var createpolicy = new TenantAuthentications()
                        {
                            TenantId = this.CurrentTenant?.Id,
                            MFA = input.MFA,
                            PrimaryAuthentication = input.PrimaryAuthentication,
                            SecondaryAuthentication = input.SecondaryAuthentication,
                            AlternateAuthentications = input.AlternateAuthentications,
                            EnableAdaptiveAuthentication = input.EnableAdaptiveAuthentication
                        };
                        await _tenantAuthenticationsRepository.InsertAsync(createpolicy,true);
                    }
    
                    return new BaseResponseDto
                    {
                        Message = "Success",
                        status = true
                    };
                }
            }
        }
    } 
    

    This is my code

    ErrorLog:

    2024-07-19 11:04:17.508 +05:30 [INF] Executing endpoint 'Volo.Abp.Identity.IdentityAuthenticationPoliciesController.GetAllAuthenticationPoliciesListAsync (Volo.Abp.Identity.Pro.HttpApi)'
    2024-07-19 11:04:17.512 +05:30 [INF] Route matched with {area = "identity", controller = "AuthenticationPolicies", action = "GetAllAuthenticationPoliciesList", page = ""}. Executing controller action with signature System.Threading.Tasks.Task`1[Volo.Abp.Application.Dtos.PagedResultDto`1[Volo.Abp.Identity.AuthPolicy.AuthPolicyResponseDto]] GetAllAuthenticationPoliciesListAsync(Volo.Abp.Identity.AuthPolicy.GetAllRequestDto) on controller Volo.Abp.Identity.IdentityAuthenticationPoliciesController (Volo.Abp.Identity.Pro.HttpApi).
    2024-07-19 11:04:17.533 +05:30 [ERR] ---------- RemoteServiceErrorInfo ----------
    {
      "code": null,
      "message": "An internal error occurred during your request!",
      "details": null,
      "data": {
        "ActivatorChain": "Volo.Abp.Identity.IdentityAuthenticationPoliciesController -> Volo.Abp.Identity.AuthPolicy.AuthenticationPolicyAppService"
      },
      "validationErrors": null
    }
    
    2024-07-19 11:04:17.534 +05:30 [ERR] An exception was thrown while activating Volo.Abp.Identity.IdentityAuthenticationPoliciesController -> Volo.Abp.Identity.AuthPolicy.AuthenticationPolicyAppService.
    Autofac.Core.DependencyResolutionException: An exception was thrown while activating Volo.Abp.Identity.IdentityAuthenticationPoliciesController -> Volo.Abp.Identity.AuthPolicy.AuthenticationPolicyAppService.
     ---> Autofac.Core.DependencyResolutionException: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'Volo.Abp.Identity.AuthPolicy.AuthenticationPolicyAppService' can be invoked with the available services and parameters:
    Cannot resolve parameter 'Volo.Abp.Identity.AuthPolicy.ITenantAuthenticationsRepository tenantAuthenticationsRepository' of constructor 'Void .ctor(Volo.Abp.Identity.AuthPolicy.IAuthenticationPolicyRepository, Volo.Abp.Identity.AuthPolicy.ITenantAuthenticationsRepository, Volo.Abp.Identity.IIdentityUserRepository, Volo.Abp.Identity.IOrganizationUnitRepository, Volo.Abp.Domain.Repositories.IRepository`1[Volo.Abp.Identity.IdentityUserOrganizationUnit])'.
       at Autofac.Core.Activators.Reflection.ReflectionActivator.&lt;&gt;c__DisplayClass12_0.&lt;UseSingleConstructorActivation&gt;b__0(ResolveRequestContext ctxt, Action`1 next)
       at Autofac.Core.Resolving.Middleware.DisposalTrackingMiddleware.Execute(ResolveRequestContext context, Action`1 next)
       at Autofac.Builder.RegistrationBuilder`3.<>c__DisplayClass41_0.<PropertiesAutowired>b__0(ResolveRequestContext ctxt, Action`1 next)
       at Autofac.Extras.DynamicProxy.RegistrationExtensions.&lt;&gt;c__DisplayClass8_0`3.<EnableInterfaceInterceptors>b__1(ResolveRequestContext ctxt, Action`1 next)
       at Autofac.Core.Resolving.Middleware.ActivatorErrorHandlingMiddleware.Execute(ResolveRequestContext context, Action`1 next)
       --- End of inner exception stack trace ---
       at Autofac.Core.Resolving.Middleware.ActivatorErrorHandlingMiddleware.Execute(ResolveRequestContext context, Action`1 next)
       at Autofac.Core.Resolving.Middleware.SharingMiddleware.Execute(ResolveRequestContext context, Action`1 next)
       at Autofac.Core.Resolving.Middleware.CircularDependencyDetectorMiddleware.Execute(ResolveRequestContext context, Action`1 next)
       at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, ResolveRequest request)
       at Autofac.Core.Resolving.ResolveOperation.ExecuteOperation(ResolveRequest request)
       at Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable`1 parameters, Object& instance)
       at Autofac.ResolutionExtensions.ResolveService(IComponentContext context, Service service, IEnumerable`1 parameters)
       at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.&lt;&gt;c__DisplayClass6_0.&lt;CreateControllerFactory&gt;g__CreateController|0(ControllerContext controllerContext)
       at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
       at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
    --- End of stack trace from previous location ---
       at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.&lt;InvokeNextExceptionFilterAsync&gt;g__Awaited|26_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
    2024-07-19 11:04:17.536 +05:30 [ERR] ---------- Exception Data ----------
    ActivatorChain = Volo.Abp.Identity.IdentityAuthenticationPoliciesController -> Volo.Abp.Identity.AuthPolicy.AuthenticationPolicyAppService
    
    2024-07-19 11:04:17.552 +05:30 [INF] Executing ObjectResult, writing value of type 'Volo.Abp.Http.RemoteServiceErrorResponse'.
    2024-07-19 11:04:17.557 +05:30 [INF] Executed action Volo.Abp.Identity.IdentityAuthenticationPoliciesController.GetAllAuthenticationPoliciesListAsync (Volo.Abp.Identity.Pro.HttpApi) in 44.0186ms
    2024-07-19 11:04:17.557 +05:30 [INF] Executed endpoint 'Volo.Abp.Identity.IdentityAuthenticationPoliciesController.GetAllAuthenticationPoliciesListAsync (Volo.Abp.Identity.Pro.HttpApi)'
    2024-07-19 11:04:17.557 +05:30 [INF] Request finished HTTP/2 GET https://localhost:44347/api/identity/authentication-policies/authentication-policies-list - - - 500 - application/json;+charset=utf-8 74.7870ms
    2024-07-19 11:04:17.602 +05:30 [INF] Background job started
    2024-07-19 11:04:17.605 +05:30 [INF] Background job complted!! it will run agian
    2024-07-19 11:04:20.621 +05:30 [INF] Background job started
    2024-07-19 11:04:20.630 +05:30 [INF] Background job complted!! it will run agian
    2024-07-19 11:04:23.642 +05:30 [INF] Background job started
    
  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    Thanks. I see the error is

    
    Cannot resolve parameter 'Volo.Abp.Identity.AuthPolicy.ITenantAuthenticationsRepository tenantAuthenticationsRepository' of constructor
    
    'Void .ctor(
        Volo.Abp.Identity.AuthPolicy.IAuthenticationPolicyRepository,
        Volo.Abp.Identity.AuthPolicy.ITenantAuthenticationsRepository,        
        Volo.Abp.Identity.IIdentityUserRepository, Volo.Abp.Identity.IOrganizationUnitRepository,  Volo.Abp.Domain.Repositories.IRepository`1[Volo.Abp.Identity.IdentityUserOrganizationUnit])'.
    

    Please share the code of ITenantAuthenticationsRepository and your ef core module

    Thanks.

  • User Avatar
    0
    Vilasini created

    hello sure PFB code :

    Entity table: AuthenticationPolicy
     
    public class AuthenticationPolicy : FullAuditedEntity<Guid>, IMultiTenant
    {
        public Guid? TenantId { get; set;}
        public string Name { get; set;}
        public string Identity { get; set; }
        public IdentityType IdentityType { get; set;}
        public int MFALevels { get; set;}
        public string Authentications { get; set; }
        public string AlternateAuthentications { get; set; }
    
    }
     
    Repository Declaration:
    
    public  interface IAuthenticationPolicyRepository : IRepository<AuthenticationPolicy, Guid>
    {
        Task<List<AuthenticationPolicy>> GetListAsync(
            string filterText = null,
            string policyName=null,
            string sorting = null,
            int maxResultCount = int.MaxValue,
            int skipCount = 0,
            CancellationToken cancellationToken = default
        );
        Task<long> GetCountAsync(
            string filterText = null,
            string policyName=null,
            CancellationToken cancellationToken = default);
    }
     
    Repository Implimentation:
    
    public  class EFCoreAuthenticationPolicyRepository : EfCoreRepository<IdentityProDbContext, AuthenticationPolicy, Guid>, IAuthenticationPolicyRepository
    {
        public EFCoreAuthenticationPolicyRepository(IDbContextProvider<IdentityProDbContext> dbContextProvider)
            : base(dbContextProvider)
        {
        }
        public async Task<long> GetCountAsync(
            string filterText = null, 
            string policyName = null, 
            CancellationToken cancellationToken = default)
        {
            var query = ApplyFilter((await GetDbSetAsync()), filterText, policyName);
            return await query.LongCountAsync(GetCancellationToken(cancellationToken));
        }
        public async Task<List<AuthenticationPolicy>> GetListAsync(
            string filterText = null, 
            string policyName = null, 
            string sorting = null, 
            int maxResultCount = int.MaxValue,
            int skipCount = 0,
            CancellationToken cancellationToken = default)
        {
            var query = ApplyFilter((await GetQueryableAsync()), filterText, policyName);
            query = query.OrderBy(string.IsNullOrWhiteSpace(sorting) ? AuthenticationPolicyConsts.GetDefaultSorting(false) : sorting);
            return await query.PageBy(skipCount, maxResultCount).ToListAsync(cancellationToken);
        }
        protected virtual IQueryable<AuthenticationPolicy> ApplyFilter(
            IQueryable<AuthenticationPolicy> query,
            string filtertext,
            string policyName=null)
        {
            return query.WhereIf(!string.IsNullOrWhiteSpace(filtertext), e => e.Name.Contains(filtertext))
                        .WhereIf(!string.IsNullOrWhiteSpace(policyName), e => e.Name.Contains(policyName));
        }
    }
     
    Entity table: TenantAuthentications 
    public class TenantAuthentications : FullAuditedEntity<Guid>,IMultiTenant
    {
        public Guid? TenantId { get; set; }
        public bool MFA { get; set; }
        public AuthenticationOptions PrimaryAuthentication { get; set; }
        public AuthenticationOptions SecondaryAuthentication { get; set; }
        public string AlternateAuthentications { get; set; }
        public bool EnableAdaptiveAuthentication { get; set; }
    }
     
    Repository Declaration :
     
    using Volo.Abp.Domain.Repositories;
    namespace Volo.Abp.Identity.AuthPolicy
    {
        public interface ITenantAuthenticationsRepository : IRepository<TenantAuthentications, Guid>
        {
        }
    }
     
    Repository Implimentation
    public class EFCoreTenantAuthenticatiosRepository : EfCoreRepository<IdentityProDbContext, TenantAuthentications, Guid>, ITenantAuthenticationsRepository
    {
        public EFCoreTenantAuthenticatiosRepository(IDbContextProvider<IdentityProDbContext> dbContextProvider)
            :base(dbContextProvider)
        {
        }
    }
     
    Efcore web module
     
    typeof(AbpIdentityProDomainModule),
        typeof(AbpIdentityEntityFrameworkCoreModule))]
    public class AbpIdentityProEntityFrameworkCoreModule : AbpModule
    {
        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            context.Services.AddAbpDbContext<IdentityProDbContext>(options =>
            {
                options.ReplaceDbContext<IIdentityDbContext, IIdentityProDbContext>();
            });
        }
        public override void OnApplicationInitialization(ApplicationInitializationContext context)
        {
        }
    }
    
  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    Your TenantAuthentications is an entity instead of AggregateRoot.

    You can try to add

     options.AddRepository<TenantAuthentications, EFCoreTenantAuthenticatiosRepository>();
    

    https://docs.abp.io/en/abp/latest/Entities#entities https://docs.abp.io/en/abp/latest/Entities#aggregateroot-class

  • User Avatar
    0
    Vilasini created

    hi Maliming , i have tried above but still im not able to test my Api function it is not at all hitting the controller can you please help

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    Is there any exception?

    Can you share a simple project?

    liming.ma@volosoft.com

    Thanks

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    I have shared the project with you.

  • User Avatar
    0
    Vilasini created

    hi maliming , Able to use the controller Thanks a lot . can you please explain where the issue occurred and how we can identify it , where do we need to fix the code if there is any Thanks

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    1.

    add two DbSet to IIdentityProDbContext

    DbSet<TenantAuthentications> TenantAuthentications { get; }
    DbSet<AuthenticationPolicy> AuthenticationPolicy { get; }
    

    2.

    AddRepository in AbpIdentityProEntityFrameworkCoreModule

    options.AddRepository<TenantAuthentications, EFCoreTenantAuthenticationsRepository>();
    options.AddRepository<AuthenticationPolicy, EFCoreAuthenticationPolicyRepository>();
    

    3.

    Rename EFCoreTenantAuthenticatiosRepository to EFCoreTenantAuthenticationsRepository

    4.

    Remove IRepository<IdentityUserOrganizationUnit>from AuthenticationPolicyAppService

  • User Avatar
    0
    Vilasini created

    hi mailiming, i need to use the IdentityUserOrganizationUnit in my existing project scenario how can i use it as a Repository. Thanks

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    You can inject the IOrganizationUnitRepository or IBasicRepository<OrganizationUnit, Guid>

    Using IOrganizationUnitRepository is the recommended way.

  • User Avatar
    0
    Vilasini created

    hello maliming thanks for the help issue is resolved

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    : )

Made with ❤️ on ABP v9.1.0-preview. Updated on December 13, 2024, 06:09