Сбой фонового задания: "Текущий пользователь не вошел в приложение"
Использование MVC jQuery .NET Core с использованием фонового задания Abp
У меня есть фоновая работа, которая правильно ставится в очередь, и я вижу работу в БД.
Однако регистрация показывает, что я получаю ошибку авторизации (см. Ниже), несмотря на то, что я вошел в систему. У меня есть те же атрибуты AbpAuthorize, которые размещены в сервисах и фоновых заданиях.
Не уверен, как продолжить отладку проблемы - любые предложения приветствуются.
СЕРВИСНЫЙ КОД С ИСПОЛЬЗОВАНИЕМ / УВЕЛИЧЕНИЕМ РАБОТЫ:
public async Task BulkImportBackground(IList<CreatePracticeDto> inputs)
{
await _backgroundJobManager.EnqueueAsync<ImportBulkPracticesBackgroundJob, ImportBulkPracticesBackgroundJobArgs>(
new ImportBulkPracticesBackgroundJobArgs
{
CreatePracticeDtos = inputs
});
_backgroundJobManager.Start();
}
КОД РАБОТЫ
using Abp.Authorization;
using Abp.BackgroundJobs;
using Abp.Dependency;
using Abp.Modules;
using Gp.Authorization;
using Gp.Ccre.ImportResult;
using Gp.Ccre.ImportResult.Dtos;
using Gp.Ccre.Practice.Dtos;
using System;
using System.Collections.Generic;
using System.Linq;
using Abp.Domain.Uow;
namespace Gp.Ccre.Practice.BackgroundJobs
{
[DependsOn(
typeof(IPracticeAppService),
typeof(IImportResultsAppService))]
[AbpAuthorize(PermissionNames.Pages_Practices, RequireAllPermissions = false)]
public class ImportBulkPracticesBackgroundJob : BackgroundJob<ImportBulkPracticesBackgroundJobArgs>, ITransientDependency
{
private readonly IPracticeAppService _practiceAppService;
private readonly IImportResultsAppService _importResultsAppService;
public ImportBulkPracticesBackgroundJob(IImportResultsAppService importResultsAppService, IPracticeAppService practiceAppService)
{
_practiceAppService = practiceAppService;
_importResultsAppService = importResultsAppService;
}
public override void Execute(ImportBulkPracticesBackgroundJobArgs args)
{
IList<CreateImportResultDto> createResultsDto = new List<CreateImportResultDto>();
var k = 0;
DateTime importedOn = DateTime.Now;
foreach (CreatePracticeDto createDto in args.CreatePracticeDtos)
{
k++;
try
{
//this correctly automatically ignores 'soft' deleted records.
var count = _practiceAppService.GetAllIdName().Result.Count(x => x.Name.Equals(createDto.Name, StringComparison.CurrentCultureIgnoreCase));
if (count > 0)
{
createResultsDto.Add(new CreateImportResultDto
{
Row = k,
Name = createDto.Name,
Message = "Already exists. Skipped.",
MessageType = AppConsts.ImportMessageType.Warning.ToString(),
ImportedOn = importedOn
});
continue;
}
// ** GOOGLE MAP API CALL **
var coordinatesFound = false; //_practiceAppService.TryGetGeoCodeAddress(createDto);
createDto.ImportedOn = importedOn;
// *** SAVE SINGLE ****
_practiceAppService.Create(createDto);
createResultsDto.Add(new CreateImportResultDto
{
Row = k,
Name = createDto.Name,
Message = "Successful.",
MessageType = AppConsts.ImportMessageType.Info.ToString(),
ImportedOn = importedOn,
GoogleMapCoordinatesFound = coordinatesFound
});
}
catch (Exception e)
{
createResultsDto.Add(new CreateImportResultDto
{
Row = k,
Name = createDto.Name,
Message = e.Message,
MessageType = AppConsts.ImportMessageType.Error.ToString(),
ImportedOn = importedOn
});
continue;
}
}
//*** SAVE RESULTS ***
foreach (var resultDto in createResultsDto)
{
_importResultsAppService.Create(resultDto);
}
CurrentUnitOfWork.SaveChanges();
}
}
[Serializable]
public class ImportBulkPracticesBackgroundJobArgs
{
public IList<CreatePracticeDto> CreatePracticeDtos { get; set; }
}
}
STACK TRACE (частично)
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> Abp.Authorization.AbpAuthorizationException: Current user did not login to the application!
at Abp.Authorization.AuthorizationHelper.AuthorizeAsync(IEnumerable`1 authorizeAttributes) in D:\Github\aspnetboilerplate\src\Abp\Authorization\AuthorizationHelper.cs:line 43
at Abp.Authorization.AuthorizationHelper.CheckPermissions(MethodInfo methodInfo, Type type) in D:\Github\aspnetboilerplate\src\Abp\Authorization\AuthorizationHelper.cs:line 98
at Abp.Authorization.AuthorizationHelper.AuthorizeAsync(MethodInfo methodInfo, Type type) in D:\Github\aspnetboilerplate\src\Abp\Authorization\AuthorizationHelper.cs:line 57
at Nito.AsyncEx.Synchronous.TaskExtensions.WaitAndUnwrapException(Task task)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location where exception was thrown ---
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)
--- End of stack trace from previous location where exception was thrown ---
at Nito.AsyncEx.Synchronous.TaskExtensions.WaitAndUnwrapException(Task task)
at Nito.AsyncEx.AsyncContext.Run(Func`1 action)
at Abp.Authorization.AuthorizationInterceptor.Intercept(IInvocation invocation) in D:\Github\aspnetboilerplate\src\Abp\Authorization\AuthorizationInterceptor.cs:line 20
at Castle.DynamicProxy.AbstractInvocation.Proceed()
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Abp.BackgroundJobs.BackgroundJobManager.TryProcessJob(BackgroundJobInfo jobInfo) in D:\Github\aspnetboilerplate\src\Abp\BackgroundJobs\BackgroundJobManager.cs:line 119
1 ответ
Решение
Проблема была вызвана попыткой внедрить службу в фоновое задание. придерживайтесь IRepository и все хорошо.