Mvc icon indicating copy to clipboard operation
Mvc copied to clipboard

Model binder is not used if model has no public property

Open gisek opened this issue 11 years ago • 7 comments

It happens in 1.0.0-beta-7. I'm not sure if it's fixed in newer versions, but I cannot check it as RC1 installer crashes.

I have a model binder. I's registered properly in Startup.

    public class InstagramUserNameModelBinder : IModelBinder
    {
        public async Task<ModelBindingResult> BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelType != typeof(InstagramUserName))
            {
                return await Task.FromResult<ModelBindingResult>(null);
            }

            var nameResult = await bindingContext.ValueProvider.GetValueAsync(bindingContext.ModelName);
            var name = (string)nameResult.RawValue;
            return new ModelBindingResult(new InstagramUserName(name), bindingContext.ModelName, true);
        }
    }

I also have a class InstagramUserName which I use as a parameter in my controller

[HttpGet]
        [Route("instagram/{userName}")]
        public async Task<IActionResult> InstagramPage(InstagramUserName userName)
        {...}
public class InstagramUserName : BaseId<string>
    {
        public InstagramUserName(string userName) : base(userName) {}
    }

Accessing the controller throws an error "No parameterless constructor defined for this object." without ever entering the model binder.

Adding a fake property helps.

public class InstagramUserName : BaseId<string>
    {
        public InstagramUserName(string userName) : base(userName) {}

        public string _ { get; set; } // this helps
    }

I also wanted to bind long type to NodaTime.Instant. Due to behavior described above I couldn't use model binder for Instant directly, so I tried creating a wrapper UnixTimeStamp.

This worked, but ONLY if I used UnixTimeStamp directly in controller. If UnixTimeStamp was a property in my model, model binders were NOT entered again.

public class UnixTimeStamp{
    public long TimeStamp{get;set;}
    public NodaTime.Instant ToInstant(){
        return Instant.FromSecondsSinceUnixEpoch(TimeStamp);
    }
}
public class MyModel{
    public string MyText {get;set;}
    public UnixTimeStamp Time {get;set;}
}
public void ControllerAction(UnixTimeStamp time){
    // this enters model binders
}

For JSON:

{
    "myText": "foo",
    "time": 1448143742
}
public void ControllerAction([FromBody]MyModel model){
    // this does NOT enter model binders
    // model is null
    // If I use 'long' instead of 'UnixTimeStamp', the model is fine
}

It looks like a bug.

gisek avatar Nov 22 '15 03:11 gisek

@rynowak @dougbu any idea why we might have such a restriction?

Eilon avatar Nov 22 '15 21:11 Eilon

@gisek exactly how is InstagramUserNameModelBinder registered in Startup? I suspect you've placed it in the MvcOptions.ModelBinders list after MutableObjectModelBinder.

dougbu avatar Nov 22 '15 22:11 dougbu

@dougbu This way:

services.Configure<MvcOptions>(
                options =>
                {
                    options.ModelBinders.Add(new InstagramUserNameModelBinder());
                    options.ModelBinders.Add(new LocalDateModelBinder());
                });

And like I said, on certain conditions described above model binders was entered.

gisek avatar Nov 22 '15 22:11 gisek

@gisek try options.ModelBinders.Insert(0, new InstagramUserNameModelBinder())

You've updated this issue's description and the new bit seems to be about [FromBody] taking over binding completely. That's by design: Once input formatting takes over, the model binding system is not involved in getting values for anything in the bound property. It's also a separate matter from your original issue.

dougbu avatar Nov 22 '15 22:11 dougbu

@dougbu

  1. Thanks, inserting model binder at 0 index did the job. I'm closing the issue.
  2. So if the second part about [FromBody] is by design is there w way around?

gisek avatar Nov 22 '15 22:11 gisek

So if the second part about [FromBody] is by design is there w way around?

You may find ways to change Json.NET behaviour to special-case things as you wish. But the input formatters do not call back into the model binding system (except when giving up due to an error).

dougbu avatar Nov 22 '15 22:11 dougbu

@dougbu ok, thanks again

gisek avatar Nov 22 '15 22:11 gisek