簡體   English   中英

流利驗證自定義響應 ASP.NET 核心 Web API

[英]Fluent validation custom response ASP.NET Core Web API

我正在研究 ASP.NET Core 6 Web API 項目。 我們使用 Fluent Validation。 如何返回自定義響應。 請指教。

我想針對不同的驗證錯誤發送自定義響應,例如頁面、限制、日期等

這是我默認得到的響應:

  {
       "type": "",
       "title": "One or more validation errors occurred.",
       "status": 400,
       "traceId": "00-097c689850af328c49705cea77fc6fbd-0c7defe165d9693f-00",
       "errors": {
         "Page": [
           "Page value should be greater than 0"
         ],
         "Limit": [
           "Limit value should be greater than 0"
         ]
       }
}

這是我想要得到的回應:

{
  "traceId": "e45b3398-a2a5-43eb-8851-e45de1184021",
  "timestamp": "2021-06-28T00:32:06.548Z",
  "errors": [
    {
      "errorCode": "Contract Violation",
      "message": "Page should be greater than 0",
      "priority": "MEDIUM",
      "properties": {
        "name": "string",
        "value": "string"
      }
    }
  ]
}

這是我的代碼:

public async Task<IActionResult> Get([FromQuery] DataParameter input) 
{

}

public class DataParameter 
{
    public DateTime? StartDate { get; set; }
    public DateTime? EndDate { get; set; }
    public int Page { get; set; }
    public int Limit { get; set; }
}

public class QueryParameterValidator : AbstractValidator<QueryParameter>
{
    public QueryParameterValidator()
    {
        RuleFor(model => model.Page)
            .GreaterThan(0)
            .WithMessage("Page value should be greater than 0");
        RuleFor(model => model.Limit)
            .GreaterThan(0)
            .WithMessage("Limit value should be greater than 0");
    
        RuleFor(model => model.StartDate)
            .Matches(@"^\d{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])$")
            .WithMessage("Transaction from date should be in the pattern of YYYY-MM-DD");
        RuleFor(model => model.EndDate)
            .Matches(@"^\d{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])$")
            .WithMessage("Transaction to date should be in the pattern of YYYY-MM-DD");
    }
}

這是您可以遵循的完整工作演示:

Model:

public class ErrorDetail
{
    public string traceId { get; set; }
    public DateTime timestamp { get; set; }
    public List<Error> errors { get; set; } = new List<Error>();
}

public class Error
{
    public string errorCode { get; set; }
    public string message { get; set; }
    public string priority { get; set; }
    public Properties properties { get; set; }=new Properties();
}

public class Properties
{
    public string name { get; set; }
    public string value { get; set; }
}

Static class:

public static class CustomProblemDetails
{
    public static ErrorDetail ErrorDetail { get; set; } =new ErrorDetail();
    public static IActionResult MakeValidationResponse(ActionContext context)
    {
        var problemDetails = new ValidationProblemDetails(context.ModelState)
        {
            Status = StatusCodes.Status400BadRequest,
        };
        foreach (var keyModelStatePair in context.ModelState)
        {
            var errors = keyModelStatePair.Value.Errors;
            if (errors != null && errors.Count > 0)
            {
                if (errors.Count == 1)
                {
                    var errorMessage = GetErrorMessage(errors[0]);
                    ErrorDetail.errors.Add(new Error()
                    {
                        errorCode= "Contract Violation",
                        message = errorMessage,
                        priority= "MEDIUM",
                        properties= new Properties() { 
                            name = "string", 
                            value = "string" 
                        }
                    });
                }
                else
                {
                    var errorMessages = new string[errors.Count];
                    for (var i = 0; i < errors.Count; i++)
                    {
                        errorMessages[i] = GetErrorMessage(errors[i]);
                        ErrorDetail.errors.Add(new Error()
                        {
                            errorCode = "Contract Violation",
                            message = errorMessages[i],
                            priority = "MEDIUM"
                        });
                    }
                }
            }
        }
        ErrorDetail.traceId = context.HttpContext.TraceIdentifier;
        ErrorDetail.timestamp = DateTime.Now;

        var result = new BadRequestObjectResult(ErrorDetail);

        result.ContentTypes.Add("application/problem+json");

        return result;
    }
    static string GetErrorMessage(ModelError error)
    {
        return string.IsNullOrEmpty(error.ErrorMessage) ?
        "The input was not valid." :
        error.ErrorMessage;
    }
}

登記:

builder.Services.AddControllers().AddFluentValidation().ConfigureApiBehaviorOptions(options =>
{
    options.InvalidModelStateResponseFactory = CustomProblemDetails.MakeValidationResponse;
}); 

結果:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM