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

Viewed 194

I have a POST method in .Net 5 API. I have added ValidationAttribute (by inheriting from it) on some properties on the request class.

It's working as expected, But I want to add a response code along with the error message. But there is no method or properties for error or response code in ValidationAttribute.

So is there any way to do this?

I have tried to add the response code in this way, but this code doesn't get called itself.

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);
        }
    }
}

So for example, for Property1 if there is any validation error, it should return with code O1.

Edit:

As suggested by @Max in comment, I have tried by adding services.AddMvc(options => { options.Filters.Add(typeof(RequestModelValidationAttribute )); });. and then I have observed that OnActionExecuting method getas called only when validation is successfull otherwise its not called. So there should be some other work around to solve this problem.

Thank you @Max for your suggestion.

1 Answers

As said in this response and in the documentation if the controller has [ApiController] it will automatically respond a 400. If you want to disable that you need to suppress that behavior by adding

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

to you startup class. See here Then your filter will be called.

Hope this will help :)

Related