简体   繁体   中英

Creating custom model validation attribute

I'm trying to emulate the behavior of the [ApiController] attribute for model validation, however I'd like to return a JSON object I've made with the validation errors in an Error array within the JSON.

The challenge I'm facing is that I'm unsure how to access validation errors from within the Attribute and I'd like to use the attribute at the class level, so it will run on all controller methods without need of supplying the attribute for each action.

Any direction would be much appreciated.

edit: linked duplicate is how to create custom attribute. I'm looking how to access model validation errors from within an attribute.

I was able to figure out my issue. I was able to utilize ModelState.IsValid in an OnActionExecuting method to access the errors. Unfortunately I'm not familiar enough with making a class level attribute so I have to apply this to all post/patch methods in order for it to work. If someone else comes up with a way to do that easily, let me know!

Project.Structure is for formatting JSON for those curious.

using System;
using System.Collections.Generic;
using System.Linq;
using Project.Structure;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Project.Attributes
{
   public class ValidateModelAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                var errorList = new List<string>();
                foreach (var modelError in context.ModelState.Values)
                {
                    errorList.AddRange(modelError.Errors.Select(error => error.ErrorMessage));
                }

                var response = new ResponseDto<object>
                {
                    Success = false,
                    TransactionId = Guid.NewGuid().ToString(),
                    ResponseType = ResponseType.Operation.Description(),
                    Response = null,
                    Errors = errorList,
                    Warnings = null
                };

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM