Если IAsyncActionFilter предоставляет значение результата, установив для свойства Result ActionExecutingContext значение, отличное от NULL, то он не сможет вызвать следующий фильтр, вызвав ActionExecutionDelegate.
Вот подробности кода:
До изменений:
DemoFilter.cs< /p>
Код: Выделить всё
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public sealed class DemoFilter : ActionFilterAttribute
{
private readonly RoleEnumType[] AllowedRoles;
public DemoFilter(params RoleEnumType[] arrRoles)
{
if (arrRoles == null || !arrRoles.Any())
{
throw new Exception("No role passed to check.");
}
AllowedRoles = arrRoles;
}
public override void OnActionExecuting(ActionExecutingContext objContext)
{
try
{
if (!objContext.HttpContext.User.Identity.IsAuthenticated)
{
objContext.Result = new UnauthorizedResult();
return;
}
UserInfoRes userinfo = GetUserDetails(objContext.HttpContext.User.GetEmail().ToLower());
if (userinfo == null || !AllowedRoles.Contains(userinfo.RoleId.ToEnum()))
{
objContext.Result = new BadRequestResult();
return;
}
}
catch (Exception)
{
throw;
}
}
}
DemoFilter.cs
Код: Выделить всё
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public sealed class DemoFilter(params RoleEnumType[] arrRoles) : ActionFilterAttribute
{
private readonly RoleEnumType[] _arrRoles = arrRoles.IsNotNull();
public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
// Throw error in case context is null
context.ThrowIfNull(nameof(context));
// Get instance of ILogger
ILogger logger = context.HttpContext.RequestServices.GetRequiredService().IsNotNull();
try
{
await ValidateUserRoleAsync(context, logger);
await next(); // Proceed to the next action filter or action method
}
catch (Exception ex)
{
logger.Error(ex, "An error occurred while executing the AllowRoles filter.");
throw;
}
}
private async Task ValidateUserRoleAsync(ActionExecutingContext context, ILogger logger)
{
// Check if the user is authenticated
if (!(context.HttpContext.User.Identity?.IsAuthenticated).GetValueOrDefault())
{
// Log a warning using the provided logger
logger.Warning($"Unauthorized request: User is not authenticated.");
// Set the result of the action context to a UnauthorizedObjectResult with the error message
context.Result = new UnauthorizedObjectResult("Unauthorized request: User is not authenticated");
return;
}
// Get user details based on email and userLocationId
var userInfo = await userValidationRepository.GetLoggedInUserDetailsAsync1(email, userLocationId);
if (userInfo is null || !_arrRoles.Contains(userInfo.RoleId.ToEnum()))
{
// Log a warning using the provided logger
logger.Warning("User with email address: {email} does not have the required roles.", email);
// Set the result of the action context to a BadRequestObjectResult with the error message
context.Result = new UnauthorizedObjectResult($"User with email address: {email} does not have the required roles.");
return;
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... et-8-webap