ASP.NET Core Web API - Fluent Validation 不验证用户登录服务

问题描述 投票:0回答:1

在 ASP.NET Core-6 Web API 中,我正在实现 Fluent Validation。我有这个代码。

型号:

public class OAuthLoginRequest
{
    public string username { get; set; }
    public string password { get; set; }
}

public class OAuthLoginResponse
{
    public string response_code { get; set; }
    public string response_description { get; set; }
    public Data data { get; set; }
    public int size { get; set; }
    public string access_token { get; set; }
    public string refresh_token { get; set; }
    public string expires_in { get; set; }
    public string token_type { get; set; }
}

验证:

public class OAuthLoginRequestValidator : AbstractValidator<OAuthLoginRequest>
{
    public OAuthLoginRequestValidator()
    {
        RuleFor(user => user.username)
            .NotNull()
            .NotEmpty().WithMessage("Username field is required.");

        RuleFor(user => user.password)
            .NotNull()
            .NotEmpty().WithMessage("Password field is required.");
    }
}

验证服务:

   public async Task<OAuthLoginResponse> Login(OAuthLoginRequest payload)
    {
        var response = new OAuthLoginResponse();
        using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
        {
            try
            {
                var authEndpoint = _config.GetSection("Endpoints").GetValue<string>("authEndpoint");
                string url = baseUrl + authEndpoint;

                var request = new OAuthLoginRequest
                {
                    username = payload.username,
                    password = payload.password
                };
                var header = new Dictionary<string, string> { };

                var httpResponse = await _httpHelper.PostOrPutRequest(uri: url, methodType: HttpMethod.Post, model: request, headers: header);
                if (httpResponse != null)
                {
                    if (httpResponse.StatusCode == HttpStatusCode.OK)
                    {
                        var content = await httpResponse.Content.ReadAsStringAsync();
                        response = JsonConvert.DeserializeObject<OAuthLoginResponse>(content);
                    }
                }
                transaction.Complete();
            }
            catch (Exception ex)
            {
                _logger.Error("An Error occured " + ex.ToString());
                response = null;
            }
            return response;
        }
    }

控制器:

    [HttpPost]
    [Route(ApiRoutes.Login)]
    public async Task<ActionResult<OAuthLoginResponse>> Login([FromBody] OAuthLoginRequest request)
    {
        var result = await _myService.Login(request);
        return Ok(result);
    }

依赖注入:

public static class DIServiceExtension
{
    public static void AddDependencyInjection(this IServiceCollection services)
    {
        // Validator
        services.AddTransient<IValidator<OAuthLoginRequest>, OAuthLoginRequestValidator>();
    }
}

程序.cs:

builder.Services.AddControllers()
                .AddFluentValidation(options =>
                {
                    // Automatic Validation
                    options.AutomaticValidationEnabled = false;
                    // Automatic registration of validators in assembly
                    options.RegisterValidatorsFromAssembly(Assembly.GetExecutingAssembly());
                });

// Register Dependency Injection Service Extension
builder.Services.AddDependencyInjection();

var app = builder.Build();

我在 DIServiceExtension 中注册了它,然后在 Program.cs 中。

我故意发布没有用户名和密码的登录信息,但应用程序没有显示任何验证消息。

这是我在 Postman 中得到的:

响应正文

{
  "response_code": null,
  "response_description": null,
  "data": null,
  "size": 0,
  "access_token": null,
  "refresh_token": null,
  "expires_in": null,
  "token_type": null
}

我希望它能显示验证消息。

我该如何解决这个问题?

c# asp.net-core asp.net-core-webapi fluentvalidation
1个回答
1
投票

来自此GitHub评论

options.AutomaticValidationEnabled = false;

用于禁用自动验证功能。


方法一:自动验证

  1. 从注册 FluentValidation 服务中删除

    options.AutomaticValidationEnabled = false;

  2. 使用

    builder.Services.AddFluentValidationAutoValidation();
    启用自动验证。

using FluentValidation.AspNetCore;

builder.Services.AddControllers()
                .AddFluentValidation(options =>
                {
                    // Automatic registration of validators in assembly
                    options.RegisterValidatorsFromAssembly(Assembly.GetExecutingAssembly());
                });

builder.Services.AddFluentValidationAutoValidation();

参考:FluentValidation/FluentValidation.AspNetCore(自动验证部分)


方法2:手动验证

  1. 在控制器中,获取注入的

    IValidator<OAuthLoginRequest>
    服务。

  2. Login
    操作中,通过
    await _validator.ValidateAsync(request);
    手动执行验证。

  3. 如果验证失败,请将

    ValidationResult
    中的错误添加到
    ModelState
    中,并使用
    BadRequest
    返回响应。

public class AuthController : Controller
{
    private readonly IValidator<OAuthLoginRequest> _validator;

    public AuthController(IValidator<OAuthLoginRequest> validator)
    {
        _validator = validator;
    }

    [HttpPost]
    [Route(ApiRoutes.Login)]
    public async Task<ActionResult<OAuthLoginResponse>> Login([FromBody] OAuthLoginRequest request)
    {
        ValidationResult validationResult = await _validator.ValidateAsync(request);

        if (!validationResult.IsValid) 
        {
            // Add error into ModelState
            validationResult.AddToModelState(ModelState);

            return BadRequest(ModelState);
        }

        var result = await _myService.Login(request);
        return Ok(result);
    }
}
public static class FluentValidationExtensions 
{
    public static void AddToModelState(this ValidationResult result, ModelStateDictionary modelState) 
    {
        foreach (var error in result.Errors) 
        {
            modelState.AddModelError(error.PropertyName, error.ErrorMessage);
        }
    }
}

参考:FluentValidation 文档(手动验证部分)

© www.soinside.com 2019 - 2024. All rights reserved.