1

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.

CodeNotFound
  • 22,153
  • 10
  • 68
  • 69
Cyan
  • 1,068
  • 1
  • 12
  • 31
  • What is the purpose of a request like `https://localhost/person?Id=null&name='John'`? I would expect the request to be: `https://localhost/person?name=John`, which should work just fine, right? – StriplingWarrior Aug 03 '17 at 21:01
  • You cannot assign the text "null" to an `int`. Just omit the `id` query string and the value of `id` will be `null` –  Aug 03 '17 at 21:31
  • it is guid?, not int. also, the question is clear and it is not about omiting that variable from the call. – Cyan Aug 03 '17 at 21:40

1 Answers1

0

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.

StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
  • that might work, altough it's more like a workaround. – Cyan Aug 03 '17 at 21:29
  • @Cyan: Trying to create some kind of exception to make `"null"` equate to `null` would be a workaround--you'd be creating a hack to accommodate the client sending non-standard query syntax to the server. My suggestions are trying to *avoid* the need for a workaround. It sounds like you're using the `Person` class to represent something that isn't a `Person`, and this is forcing you to corrupt your model with changes that don't really make sense (i.e. a true "Person" should have a non-null ID, right?). – StriplingWarrior Aug 03 '17 at 22:24