简体   繁体   中英

Asp.Net Core - Model Binding For Generic Model Stopped Working After Upgrade To Core 3.0

I have an Asp.Net Core Web Api project that I just upgraded from 2.2 to 3.0. In my app I have entities were the keys can be either string, guid, int (a lot of Legacy code). In order to manage some of the API requests in a generic way, I've created this view model:

public class EntityRequestViewModel<T>
{
    [Required]
    public T Id;
}

Which I used in different controllers like

[HttpPost]
    [Route("delete")]
    public async Task<IActionResult> Delete([FromBody]EntityRequestViewModel<Guid> deleteEntityRequest)
    {
      //Do something
    }

There are also many view models extending this EntityRequestViewModel. This worked great, but for some reason, after the upgrade, the value is not bound to the Id.

The generic parameter is fine, what you are doing wrong is that this is a public field :

public T Id;

What you really need for model binding to kick in is a property with a public setter:

public T Id { get; set; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM