ASP.NET Core — плавная проверка не работает, а сведения о проверке не отображаются в теле ответаC#

Место общения программистов C#
Ответить Пред. темаСлед. тема
Anonymous
 ASP.NET Core — плавная проверка не работает, а сведения о проверке не отображаются в теле ответа

Сообщение Anonymous »

В веб-API ASP.NET Core 8 с использованием Fluent Validation с помощью Dapper и HttpClient при отправке я получил это в Swagger JSON ResponseBody:
< blockquote>
INSERT_ACCOUNT_FAILED.

Но когда я проверил файл журнала, я получил следующее:

Создание учетной записи для: строковая строка
Ошибка при получении учетных записей для мобильной строки: 06 – системе не удалось обработать ваш запрос. Повторите попытку.
Uri запроса проверки Bvn:

Не удалось получить связанную учетную запись для строки BVN. Не удалось проанализировать ответ от службы. Ответ: {"type":"https://tools.ietf.org/html/rfc7231#sec ... "Произошла одна или несколько ошибок проверки.","status":400," trackId":"00-4361bf6b632396d3200058a1771eed3b-a96c8a4aa959714b-01","errors":{"$":["Не удалось преобразовать значение JSON в BVNService.Model.BVNAssociatedRequest. Путь: $ | LineNumber: 0 | . "]>

Uri запроса проверки Bvn:

Не удалось получить связанную учетную запись по строке мобильного устройства. Не удалось проанализировать ответ от службы. Ответ: {"type":"https://tools.ietf.org/html/rfc7231#sec ... "Произошла одна или несколько ошибок проверки.","status":400," trackId":"00-4361bf6b632396d3200058a1771eed3b-995a0ff72d31d941-01","errors":{"$":["Значение JSON не удалось преобразовать в BVNService.Model.PhoneNumberAssociatedRequest Path: $ | LineNumber: 0 | . "]}

2024-05-11T11:15:57.1799214+01:00 [ERR] (/WS001ITE115/7) Не удалось получить сведения о клиенте по строке номера телефона: {"timestamp":"2024 -05-11T10:15:57.139+00:00","status":400,"error":"Неверный запрос","path":"/account/getCustomerProfileFromMobile"}

State ' строка' не найдена.

Не удалось вставить учетную запись для: строки | нет: | мн: строка. Не удалось сгенерировать номер учетной записи.

HTTP «POST» «/api/Account/CreateAccount» ответил 400 за 822,6511 мс

Я хочу получить эту проверку или более подробную информацию о теле ответа Swagger JSON, а не просто:

INSERT_ACCOUNT_FAILED

ПРИМЕЧАНИЕ. Свободная проверка не работает, и сведения о проверке не отображаются в теле ответа.
Это мой класс модели:
public class BasicResponse
{
public string ResponseCode { get; private set; }
public string ResponseDescription { get; private set; }
public string FriendlyErrorMessage { get; private set; }

// Default constructor
public BasicResponse() { }

// Constructor with ResponseCodes enum
public BasicResponse(ResponseCodes responseCode)
{
InitializeFromEnum(responseCode);
}

// Constructor with ResponseCodes enum and additional error text
public BasicResponse(ResponseCodes responseCode, string errorText)
{
InitializeFromEnum(responseCode, errorText);
}

// Constructor with custom values
public BasicResponse(string responseCode, string responseDescription, string friendlyErrorMessage)
{
ResponseCode = responseCode;
ResponseDescription = responseDescription;
FriendlyErrorMessage = friendlyErrorMessage;
}

// Initializes class from enum with optional additional description
private void InitializeFromEnum(ResponseCodes responseCode, string errorText = null)
{
ResponseCode = ((int)responseCode).ToString();
FriendlyErrorMessage = responseCode.ToString(); // Converts enum directly to string
ResponseDescription = errorText;
}

// Check if the response is successful
public bool IsSuccessful()
{
return ResponseCode == ((int)ResponseCodes.SUCCESS).ToString();
}

// Set response using a different BasicResponse
public void SetResponse(BasicResponse response)
{
if (response == null) return;

ResponseCode = response.ResponseCode;
ResponseDescription = response.ResponseDescription;
FriendlyErrorMessage = response.FriendlyErrorMessage;
}

// Set response using an enum and optional additional error text
public void SetResponse(ResponseCodes responseCode, string errorText = null)
{
InitializeFromEnum(responseCode, errorText);
}
}

DTO:
public class CreateAccountResponseDto : BasicResponse
{
public CreateAccountResponseDto()
{
}

public CreateAccountResponseDto(ResponseCodes responseEnum, string errorText) : base(responseEnum, errorText)
{
}

public string AccountNumber { get; set; }
}

UtilityHelper.cs:
public class UtilityHelper : IUtilityHelper
{
public async Task ValidateModelAsync(
IValidator validator,
T objectToValidate
)
{
if (validator == null) // Safety check for NullReferenceException
{
throw new ArgumentNullException(nameof(validator));
}

var validationResult = await validator.ValidateAsync(objectToValidate);
var validationMessages = string.Empty;

if (validationResult.IsValid)
{
return (true, string.Empty);
}

validationMessages = string.Join("\n", validationResult.Errors.Select(e => e.ErrorMessage));
return (false, validationMessages);
}
}

VALIDATOR:
public class CreateAccountRequestDtoValidator : AbstractValidator
{
private readonly IFlexcubeAccountService _flexcubeAccountService;
private readonly IDbDataAccess _dbDataAccess;

public CreateAccountRequestDtoValidator(
IDbDataAccess dbDataAccess,
IFlexcubeAccountService flexcubeAccountService)
{
_dbDataAccess = dbDataAccess ?? throw new ArgumentNullException(nameof(dbDataAccess));
_flexcubeAccountService = flexcubeAccountService ?? throw new ArgumentNullException(nameof(flexcubeAccountService));
}

public CreateAccountRequestDtoValidator()
{
#region Simple Validations
RuleFor(x => x.FirstName)
.NotEmpty()
.WithMessage("First Name is required.")
.MaximumLength(50)
.WithMessage("First Name must not exceed 50 characters.");

RuleFor(x => x.LastName)
.NotEmpty()
.WithMessage("Last Name is required.")
.MaximumLength(50)
.WithMessage("Last Name must not exceed 50 characters.");

#endregion Simple Validations

// Conditional validations
When(c => !string.IsNullOrWhiteSpace(c.Bvn) || !string.IsNullOrEmpty(c.Nin), () =>
{
RuleFor(c => c.Title)
.NotEmpty()
.WithMessage("Title is required");

RuleFor(m => m.Bvn).MustAsync(async (bvn, request, context, cancellationToken) =>
await ValidateBvn(bvn, request, context))
.WithMessage("{Message}");

RuleFor(m => m.Gender).MustAsync(async (gender, request, context, cancellationToken) =>
await ValidateGender(gender, request, context))
.WithMessage("{Message}");
#endregion
});
RuleFor(x => x.DateOfBirth)
.MustAsync(async (request, dob, context, cancellationToken) => await ValidateDateOfBirth(request, dob, context))
.WithMessage("{Message}");
}

private async Task ValidateBvn(CreateAccountRequestDto request, string bvn, ValidationContext context)
{
bool isValid = !string.IsNullOrWhiteSpace(bvn) && !string.IsNullOrWhiteSpace(request.BvnPhoneNumber);

if (!isValid)
{
context.MessageFormatter.AppendArgument("Message", "BVN phone number is required if BVN is passed.");
}

return await Task.FromResult(isValid); // Ensure asynchronous return
}

private async Task ValidateTitle(CreateAccountRequestDto request, string title, ValidationContext context)
{
var titleList = await _flexcubeAccountService.GetTitleAsync();
bool isValid = titleList.Any(t => t.Equals(title, StringComparison.InvariantCultureIgnoreCase));

if (!isValid)
{
context.MessageFormatter.AppendArgument("Message", $"{title} is not a valid title.");
}
return isValid;
}
var validator = new CreateAccountRequestDtoValidator(_dbDataAccess, _flexcubeAccountService);

var (isValid, validationErrors) = await _utilityHelper.ValidateModelAsync(validator, createAccountRequestDto);

if (!isValid)
{
return BadRequest(validationErrors);
}

var response = await _accountProcessor.AddAccountAsync(createAccountRequestDto);

if (response.IsSuccessful())
{
return Ok(response);
}

return BadRequest(response.FriendlyErrorMessage);
}

AccountProcessor:
public class AccountProcessor : IAccountProcessor
{
private readonly ILogger _logger;
private readonly IFlexcubeAccountService _flexcubeAccountService;
private readonly IDbDataAccess _dbDataAccess;
private readonly IBvnService _bvnService;
private readonly IUtilityHelper _utilityHelper;

public AccountProcessor(ILogger logger, IDbDataAccess dbDataAccess
, IFlexcubeAccountService flexcubeAccountService
, IBvnService bvnService
, IUtilityHelper utilityHelper)
{
_logger = logger;
_dbDataAccess = dbDataAccess;
_flexcubeAccountService = flexcubeAccountService;
_bvnService = bvnService;
_utilityHelper = utilityHelper;
}

public async Task AddAccountAsync(CreateAccountRequestDto createAccountDto)
{
var createAccountResponse = new CreateAccountResponseDto();

try
{
if (!string.IsNullOrWhiteSpace(createAccountDto.Bvn) || !string.IsNullOrWhiteSpace(createAccountDto.Nin) || await ValidateAccountBvnAsync(createAccountDto))
{
_logger.LogInformation($"Creating account for: {createAccountDto.FirstName} {createAccountDto.LastName}");
createAccountResponse = await CreateAccountAsync(createAccountDto);
}
else
{
_logger.LogWarning("Could not verify NIN or BVN for this account");
createAccountResponse.SetResponse(ResponseCodes.INSERT_ACCOUNT_FAILED, "Could not verify NIN or BVN for this account");
return createAccountResponse;
}

return createAccountResponse;
}
catch (Exception ex)
{
_logger.LogError($"Error in AddAccountAsync: {ex.Message}");
createAccountResponse.SetResponse(ResponseCodes.INSERT_ACCOUNT_FAILED, "An internal error occurred");
return createAccountResponse;
}
}
}

Контроллер:
[HttpPost("CreateAccount")]
public async Task CreateAccount([FromBody] CreateAccountRequestDto createAccountRequestDto)
{
var validator = new CreateAccountRequestDtoValidator(_dbDataAccess, _flexcubeAccountService);

var (isValid, validationErrors) = await _utilityHelper.ValidateModelAsync(validator, createAccountRequestDto);

if (!isValid)
{
return BadRequest(validationErrors);
}

var response = await _accountProcessor.AddAccountAsync(createAccountRequestDto);

if (response.IsSuccessful())
{
return Ok(response);
}

return BadRequest(response.FriendlyErrorMessage);
}
}

DIServiceExtension.cs:
public static class DIServiceExtension
{
public static void AddDependencyInjection(this IServiceCollection services)
{
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddTransient();
}
}

Program.cs:
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddFluentValidationAutoValidation();
builder.Services.AddFluentValidationClientsideAdapters();

builder.Services.AddDependencyInjection(); // Custom method for DI

builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAll", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
});

var app = builder.Build();


Подробнее здесь: https://stackoverflow.com/questions/784 ... s-not-bein
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Spring WebFlux ExchangeFunctions регистрирует отсутствующие сведения о теле запроса
    Anonymous » » в форуме JAVA
    0 Ответы
    18 Просмотры
    Последнее сообщение Anonymous
  • HTML: Mailto Line и новый персонаж в теле в теле
    Anonymous » » в форуме Html
    0 Ответы
    20 Просмотры
    Последнее сообщение Anonymous
  • Ошибка Bad Gateway (502) при вызове API Core Core .NET .NET из другого API Core .NET .NET .NET .NET
    Anonymous » » в форуме C#
    0 Ответы
    9 Просмотры
    Последнее сообщение Anonymous
  • Ошибка Bad Gateway (502) при вызове API Core Core .NET .NET из другого API Core .NET .NET .NET .NET
    Anonymous » » в форуме C#
    0 Ответы
    10 Просмотры
    Последнее сообщение Anonymous
  • Отобразите все сведения о резиденте после нажатия кнопки просмотра с помощью ASP.NET Core.
    Anonymous » » в форуме C#
    0 Ответы
    19 Просмотры
    Последнее сообщение Anonymous

Вернуться в «C#»