I'm using C# web api and want to create a filter to all requests.
I have a designated class to every request so I just want to add some data annotations and get the validation over with.
The problem is that I'm getting true every time on actionContext.ModelState.IsValid
I have added my filter in the config:
config.Filters.Add(new RequestValidationFilter());
validation method looks like every other in the web
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);
}
}
}
I have the following method:
[HttpPost, Route("User/Login")]
public async Task<Responses.Login> Login(Requests.Login request)
{
...//some login logic
}
And also, I have my model which is:
public class Requests
{
public class Login
{
[Required(AllowEmptyStrings = false, ErrorMessage = "Email address cannot be empty!")]
[MinLength(5)]
public string Email;
[Required]
public string Password;
}
}
I'm sending both an empty request or request which Email and Password are null and still the actionContext.ModelState.IsValid evaluate it as true
Attached is an image when email was sent but password wasn't.
Following a comment, here is my request via Advanced Rest Client chrome plugin
the image actually shows that Keys and Values are empty when in fact they are supplied..
EDIT
number of things i've also tried:
- removing all other filters, why? maybe the context was messed up by another reading.
- sending valid request in terms of fields, but email was 1 char long.why? maybe
Requiredis working differently than others, still nothing about the min-length issue. - instead of nested objects, i created a seperate stand-alone class for the
Loginobject. why? thought maybe the fact that it's nested the validation is not recursive. - Looping the
Argumentslist one-by-one and validate as object, answer is always true. never fails, why? cause Im almost admitting defeat. - instead of adding filter to config as i described in the question, tried
GlobalConfiguration.Configuration.Filters.Add(new RequestValidationFilter());instead

