MVC ICollection<IFormFile> ValidationState always set to Skipped

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-05 00:05:40

It looks like MVC is suppressing further validation if the IFormFile or a collection of IFormFile is found to be not null.

If you take a look at the FormFileModelBinder.cs code, you can see the issue right here. It is suppressing validation if the binder is able to get a non-null result from the if/elseif/else clause above.

In a test, I made a view model with code like this:

[ThisAttriuteAlwaysReturnsAValidationError]
public IFormFile Attachment { get;set; }

When I actually upload a file to this example, the always-erroring attribute above it never gets called.

Since this is coming from MVC itself, I think your best bet for this is to implement the IValidateableObject interface.

public class YourViewModel : IValidatableObject
{
    public ICollection<IFormFile> Attachments { get;set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        var numAttachments = Attachments?.Count() ?? 0;
        if (numAttachments == 0)
        {
            yield return new ValidationResult(
                "You must attached at least one file.",
                new string[] { nameof(Attachments) });
        }
    }
}

This method will still be called as it is not associated with any individual property, and thus isn't suppressed by MVC like your attribute is.

If you've got to do this in more than one place, you could create an extension method to help.

public static bool IsNullOrEmpty<T>(this IEnumerable<T> collection) =>
        collection == null || !collection.GetEnumerator().MoveNext();

Update

This has been filed as a bug and should be fixed in 1.0.0 RTM.

Partial Answer (just for code sharing purpses)

try this:

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public sealed class RequiredCollectionAttribute : ValidationAttribute
{

    public override bool IsValid(object value)
    {
        ErrorMessage = "You must provide at least one.";
        var collection = value as ICollection;

        return collection != null || collection.Count > 0;
    }
}

also, try to add a filter.

GlobalConfiguration.Configuration.Filters.Add(new RequestValidationFilter());

and write the filter itself:

public class RequestValidationFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (actionContext.ModelState.IsValid == false)
        {
            var errors = actionContext.ModelState
                                      .Values
                                      .SelectMany(m => m.Errors
                                                        .Select(e => e.ErrorMessage));

            actionContext.Response = actionContext.Request.CreateErrorResponse(
                HttpStatusCode.BadRequest, actionContext.ModelState);

            actionContext.Response.ReasonPhrase = string.Join("\n", errors);
        }
    }
}

just for us to check if a breakpoint is triggered inside the filter.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!