【问题标题】:How to add Error or response Code in the API response in .Net 5?如何在 .Net 5 的 API 响应中添加错误或响应代码?
【发布时间】:2021-11-22 09:39:51
【问题描述】:

我在 .Net 5 API 中有一个 POST 方法。我在请求类的一些属性上添加了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,如果有任何验证错误,它应该返回代码O1

编辑:

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

感谢@Max 的建议。

【问题讨论】:

  • 嗨,您是否在启动类中添加了services.AddMvc(options =&gt; { options.Filters.Add(typeof(RequestModelValidationAttribute )); }); 以全局添加您的过滤器??
  • @Max 请在编辑后检查我更新的问题

标签: c# asp.net-core asp.net-core-webapi


【解决方案1】:

正如this 响应和documentation 中所说,如果控制器具有 [ApiController],它将自动响应 400。如果您想禁用它,您需要通过添加来抑制该行为

services.Configure<ApiBehaviorOptions>(options =>
        {
            options.SuppressModelStateInvalidFilter = true;
        });

给你的创业班。 See here 然后您的过滤器将被调用。

希望这会有所帮助:)

【讨论】:

猜你喜欢
  • 2023-02-21
  • 1970-01-01
  • 1970-01-01
  • 2014-10-29
  • 1970-01-01
  • 2017-08-14
  • 2020-09-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多