NullReferenceException in custom IModelBinder

215 views Asked by At

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.

1

There are 1 answers

0
thomrand On BEST ANSWER

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.