Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC ICollection<IFormFile> ValidationState always set to Skipped

As part of an ASP.NET Core MVC 1.0 project, I have a ViewModel with an ICollection<> property. I need to validate that this collection contains one or more items. My custom validation attribute doesn't get executed.

In my instance it holds multiple file attachments from a multipart/form-data form.

I have decorated the property in the ViewModel with a custom validation attribute:

[RequiredCollection]
public ICollection<IFormFile> Attachments { get; set; }

Below is the custom attribute class. It simply checks the collection is not null and has greater than zero elements:

public class RequiredCollectionAttribute : ValidationAttribute
{
    protected const string DefaultErrorMessageFormatString = "You must provide at least one.";

    public RequiredCollectionAttribute() : base(DefaultErrorMessageFormatString) { }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var collection = (ICollection) value;

        return collection == null || collection.Count > 0
            ? ValidationResult.Success
            : new ValidationResult(ErrorMessageString);
    }
}

And finally, in the controller I am ensuring the ViewModel in the POST request is valid, which should trigger the validation:

[HttpPost]
public async Task<IActionResult> Method(MethodViewModel viewModel)
{
    if (!ModelState.IsValid)
        return View(viewModel);
    ...
}

If I break at the ModelState.IsValid call, the contents of ModelState.Values for the Attachments property is:

Visual Studio Locals Window

Question

  • Why doesn't my breakpoint within the RequiredCollectionAttribute.IsValid() method ever get hit?
  • Why does the ValidationState get set to Skipped for the Attachments property?

--

Edit 1:

MethodViewModel definition, as requested:

public class MethodViewModel
{
    ...
    [Display(Name = "Attachments")]
    [RequiredCollection(ErrorMessage = "You must attached at least one file.")]
    public ICollection<IFormFile> Attachments { get; set; }
    ...
}

--

Edit 2:

Below is the trimmed value of actionContext.ModelState (exported in JSON), as requested. This is the state when a breakpoint is hit on entry to a global action filter, OnActionExecuting():

{
    "Count": 19,
    "ErrorCount": 0,
    "HasReachedMaxErrors": false,
    "IsReadOnly": false,
    "IsValid": true,
    "Keys": 
    [
        "Attachments"
    ], 
    "MaxAllowedErrors": 200,
    "ValidationState": Valid,
    "Values": 
    [
        {
            "AttemptedValue": null,
            {
            }, 
            "RawValue": null,
            "ValidationState": Microsoft.AspNet.Mvc.ModelBinding.ModelValidationState.Skipped
        }
    ], 
    {
        [
            "Key": "Attachments",
            {
                "AttemptedValue": null,
                "RawValue": null,
                "ValidationState": Microsoft.AspNet.Mvc.ModelBinding.ModelValidationState.Skipped
            }, 
            "key": "Attachments",
            {
                "AttemptedValue": null,
                "RawValue": null,
                "ValidationState": Microsoft.AspNet.Mvc.ModelBinding.ModelValidationState.Skipped
            } 
        ]
    } 
}

--

Edit 3:

The view's razor syntax to render the Attachments input field.

<form role="form" asp-controller="Controller" asp-action="Method" method="post" enctype="multipart/form-data">
    ...
    <div class="form-group">
        <label asp-for="Attachments" class="control-label col-xs-3 col-sm-2"></label>
        <div class="col-xs-9 col-sm-10">
            <input asp-for="Attachments" class="form-control" multiple required>
            <span asp-validation-for="Attachments" class="text-danger"></span>
        </div>
    </div>
    ...
</form>
like image 356
Chris Pickford Avatar asked Mar 14 '16 14:03

Chris Pickford


2 Answers

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.

like image 85
Will Ray Avatar answered Nov 02 '22 12:11

Will Ray


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.

like image 1
Ori Refael Avatar answered Nov 02 '22 10:11

Ori Refael