asp.net-mvc.net-4.5modelbinder

NullReferenceException in custom IModelBinder


I'm trying to implement my own custom ModelBinder using MVC4 in .NET 4.5, but get the weirdest error. My code looks approx. like this

TableViewModelModel : IModelBinder

public object BindModel(ControllerContext ctx, BindingContext btx)
{
    IEnumerable<String> sSearch = ctx.HttpContext.Request.Params.Keys.OfType<String().Where(key => key.StartsWith("sSearch_"));
    ...
}

A NullReferenceException is thrown allready at the first line, but none of the properties are actually null (they all appear in the intellisense debug). In a desperate I decided to rid of some of the properties to get a better look at where the exception is thrown and I found the culprit to be the Params property. What's really strange is that all the keys from the querystring is listed in the debug window, but an exception is thrown nevertheless. I really need some help on this one people!

Thanks.


Solution

  • Found the error using Reflector and analyzing the stack trace. Turns out that somewhere along the call stack HttpRequest.Params tried to read the Identity property of my Principal object (HttpContext.User). I have a custom implementation of IPrincipal that doesn't initialize the Identity object - and there you have it.

    A big thank you to those of you who took the time to read my question.