1
votes

When creating a webApi controller, where the only parameter passed is a string, can I apply a validator attribute for 'Required', or 'String Length'?

This does not seem to work for me...

Example of controller action:

[HttpPost]
[ActionName("GetInventoryDetails")]
public HttpResponseMessage GetInventoryDetails([FromBody][Required][StringLength(20)]string serialNumber)
{
    if (ModelState.IsValid == true)
    {            
        var response = Request.CreateResponse(statusCode: HttpStatusCode.OK, value: string.Empty, mediaType: Request.Content.Headers.ContentType);
        return response;
    }
    else
    {
        var response = Request.CreateResponse(statusCode: HttpStatusCode.BadRequest);
        return response;
    }
}

when I pass in a string longer than 20 characters ModelState.IsValid is true. Also, if I pass no parameter ModelState.IsValid is also true. In both cases I was expecting ModelState.IsValid to be false.

BTW - if instead I construct a controller action to accept an object instead of a string, and if I place attribute validators on properties of the class then validation works as expected, and ModelState.IsValid shows false. It is only when trying to use attribute validators inline as in my example above where the ModelState.IsValid is showing an unexpected result.

2
I think your last para pretty much answers your question, no? - spender
Well, not sure I answered my own question. Perhaps I am not doing it correctly. Perhaps it works if done a different way... - barrypicker
You can read here on how you can implement that yourself: blog.markvincze.com/… - Evk
@Evk - unfortunately my company blocks the site you recommend... :( - barrypicker

2 Answers

3
votes

You answered your own question in that it does NOT work. However the attribute usage is defined as

[AttributeUsageAttribute(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]

Since Parameter is allowed it would seem like it could work but obviously not. Now you could create your own action attribute that you could then enforce the validation from.

1
votes

I suspect the issue is in your HTTP request. The request needs to be formatted slightly differently if you're accepting an object or a single string parameter.

If you accept an object (the way you said works) then the body of your request would be a JSON object with a property called serialNumber:

{ serialNumber: "serial1234" }

However, if you accept only a single string parameter, then according to the documentation, the body of your request should be "a raw JSON string (not a JSON object)". So it should look something like this:

"serial1234"

The quotes are only needed if the Content-Type on your request is "application/json". If you send it as "text/plain", then you probably don't need the quotes.