2

I'm using asp.net web-api and trying to catch 2 situations:

  1. an undefined Uri parameter is passed
  2. an invalid value for the Uri parameter is passed

Parameters and value bind successfully, but when either the name or the value are invalid, no exception occurs and a null is passed.

More details:
ModelState.IsValid is always true
I have cleared all formatters Using GlobalConfiguration.Configuration.Formatters.Clear(); and then adding my inherited XmlMediaTypeFormatter which sets XmlSerializer = true
Also I'm using a schema generated classes (xsd tool) for the complex types

This is the controller method signature:

public Messages GetMessages(int? startId = null, int? endId = null, DateTime? startDate = null, DateTime? endDate = null, int? messageType = null, string clientId = "", bool isCommentsIncluded = false)

Any ideas?

Abir
  • 103
  • 8

1 Answers1

2

Create a class and decorate the attributes you wish to validate against. E.g (Obviously, use your own values)

public class ModelViewModel
{
    public int Id { get; set; }
    [Required]
    public int RelationshipId { get; set; }
    [Required]
    public string ModelName { get; set; }
    [Required]
    public string ModelAttribute { get;set; }
}

Create a filter, so you don't have to use Model.IsValid throughout every controller.

public class ValidationFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var modelState = actionContext.ModelState;

        if (!modelState.IsValid)
            actionContext.Response = actionContext.Request
                 .CreateErrorResponse(HttpStatusCode.BadRequest, modelState);
    }
}

Finally add the below to your Application_Start() in your Global.asax

GlobalConfiguration.Configuration.Filters.Add(new ValidationFilter());

Hope this helps.

Update

public Messages GetMessages([FromUri] ModelViewModel model)

Your model class will now be bound to the values in the uri checkout this question

Community
  • 1
  • 1
TYRONEMICHAEL
  • 4,174
  • 4
  • 30
  • 47
  • Thanks, but I'm not sure I understand your solution How can this be used for simple types passing on the Uri, use this single class instead of the simple types? – Abir Sep 09 '13 at 07:43
  • I don't know what have changed in my code, but I'm now getting the ModelState.IsValid updated correctly. It's good to know about another option to do this, as you suggest, but it doesn't apply to detecting any misspelled parameter – Abir Sep 15 '13 at 16:02