如何在 .Net 5 的 API 响应中添加错误或响应代码?

How to add Error or response Code in the API response in .Net 5?

我在 .Net 5 API 中有一个 POST 方法。我在请求 class.

的某些属性上添加了 ValidationAttribute(通过继承)

它按预期工作,但我想添加响应代码和错误消息。但是 ValidationAttribute.

中没有错误或响应代码的方法或属性

那么有什么办法可以做到这一点吗?

我曾尝试以这种方式添加响应代码,但此代码本身并未被调用。

services.AddScoped<RequestModelValidationAttribute>(); //Code for dependency  injection

public class RequestModelValidationAttribute : ActionFilterAttribute
{

    ResponseModel<ResponseAPI> apiResponse = new ResponseModel<ResponseAPI>
    {
        ResponseCode = "01",
        ResponseMessage = "One or more validation errors occurred.",
    };

    /// <summary>
    /// OnActionExecuting
    /// </summary>
    /// <param name="context"></param>
    public override void OnActionExecuting(ActionExecutingContext context)
    {

        if (!context.ModelState.IsValid)
        {
            foreach (var modelState in context.ModelState)
            {
                if (modelState.Value.ValidationState == Microsoft.AspNetCore.Mvc.ModelBinding.ModelValidationState.Invalid)
                {
                    switch (modelState.Key)
                    {
                        case "Property1":
                            apiResponse.ResponseCode = "01";
                            apiResponse.Errors.Add(modelState.Key, modelState.Value.Errors.Select(a => a.ErrorMessage).ToList());
                            break;
                        case "Property2":
                            apiResponse.ResponseCode = "02";
                            apiResponse.Errors.Add(modelState.Key, modelState.Value.Errors.Select(a => a.ErrorMessage).ToList());
                            break;
                        case "Property3":
                            apiResponse.ResponseCode = "03";
                            apiResponse.Errors.Add(modelState.Key, modelState.Value.Errors.Select(a => a.ErrorMessage).ToList());
                            break;
                    }

                    break;
                }

            }
            context.Result = new BadRequestObjectResult(apiResponse);
        }

        if (apiResponse.Errors.Count > 0)
        {
            context.Result = new BadRequestObjectResult(apiResponse);
        }
    }
}

例如,对于 Property1 如果有任何验证错误,它应该 return 代码 O1.

编辑:

正如@Max 在评论中所建议的,我尝试添加 services.AddMvc(options => { options.Filters.Add(typeof(RequestModelValidationAttribute )); });。然后我观察到 OnActionExecuting 方法只有在验证成功时才会被调用,否则不会被调用。所以应该有一些其他的解决方法来解决这个问题。

谢谢@Max 的建议。

response and in the documentation 中所述,如果控制器具有 [ApiController],它将自动响应 400。如果你想禁用它,你需要通过添加

来抑制该行为
services.Configure<ApiBehaviorOptions>(options =>
        {
            options.SuppressModelStateInvalidFilter = true;
        });

给你启动class。 See here 然后你的过滤器将被调用。

希望这会有所帮助:)