Web Api Required Parameter

前端 未结 5 808
闹比i
闹比i 2020-12-14 06:10

Using ASP.NET Web API. Is there a way to automatically return a status code 400 if a parameter is null? I found this question but that is a global solution that is applied

5条回答
  •  抹茶落季
    2020-12-14 06:52

    The accepted solution takes it upon itself to report back any errors. A more appropriate approach for MVC5 is to let the controller handle (via model validation) the reporting of any errors, aka something like this:

    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Web.Http.Controllers;
    using System.Web.Http.Filters;
    using System.Web.Http.ModelBinding;
    
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
    public sealed class ValidateParametersAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext context)
        {
            var descriptor = context.ActionDescriptor;
            if (descriptor != null)
            {
                var modelState = context.ModelState;
                foreach (var parameterDescriptor in descriptor.GetParameters())
                {
                    EvaluateValidationAttributes(
                        suppliedValue: context.ActionArguments[parameterDescriptor.ParameterName],
                        modelState: modelState,
                        parameterDescriptor: parameterDescriptor
                    );
                }
            }
    
            base.OnActionExecuting(context);
        }
    
        static private void EvaluateValidationAttributes(HttpParameterDescriptor parameterDescriptor, object suppliedValue, ModelStateDictionary modelState)
        {
            var parameterName = parameterDescriptor.ParameterName;
    
            parameterDescriptor
                .GetCustomAttributes()
                .OfType()
                .Where(x => !x.IsValid(suppliedValue))
                .ForEach(x => modelState.AddModelError(parameterName, x.FormatErrorMessage(parameterName)));
        }
    }
    
    
    

    You may then plug it in universally via WebApiConfig.cs:

    config.Filters.Add(new ValidateParametersAttribute());
    

    提交回复
    热议问题