Exclude "The value 'null' is not valid for ..." in ActionFilterAttribute

2.2k Views Asked by At

In a webapi project we have a model like:

public class Person
{
    public string Name { get; set; }

    public Guid? Id { get; set; }
}

We have configured validation of parameters and we do some checks using ActionFilterAttribute:

public class ModelActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        (...)
        var modelState = actionContext.ModelState;
        if (modelState.IsValid == false)
        {
            actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, modelState);
        }

        base.OnActionExecuting(actionContext);
    }
}

The problem is that, doing a call like: https://localhost/person?Id=null&name='John', creates an error like:

The value 'null' is not valid for Id.

We have made the Id field nullable in the first place because we want to allow calls like the one above. Still, the validator complains. Is there any clean way to exclude this error?

I could go and iterate through the list of errors and exclude this one, but it feels really wrong.

1

There are 1 best solutions below

2
On BEST ANSWER

You could define a model specific to the purpose. For example:

public class PersonSearchParameters
{
    public string Name { get; set; }

    public string Id { get; set; }
}

Then allow your method to handle parsing Id in the way you'd prefer to handle it.

I really think it'll be easier, though, if you just say that id should be omitted from your results if you want it to be null.