2

Estoy intentado crear un AJAX request que envie un objeto (el cual he llamado MainObject) al servidor Asp.Net CORE. El problema es que este objeto contiene otro el cual hereda de un objeto base (NestedObject hereda de BaseObject).

Entonces, cuando envio el objeto, el método del controller es llamado y en lugar de recibir el MainObject con un NestedObject como parámetro, recibo un MainObject con el BaseObject. Es decir, como que no sabe que ese objeto no es de la clase base sino del que hereda. He probado a añadir la propiedad $type al objeto pero tampoco ha funcionado.

Alguien tiene alguna idea de como solucionar este problema? Gracias.

Clases

class BaseObject
{
    public string Id { get; set; }
}

class NestedObject : BaseObject
{
    public string Property1 { get; set; }
    public string Property2 { get; set; }
}

class MainObject 
{
    public string Id { get; set; }
    public BaseObject Item { get; set; }
}

Controller

[HttpPost]
public async Task<MainObject> CreateObject(MainObject mainObject)
{
    if (mainObject.Item is NestedObject) {
        NestedObject nestedObject = mainObject.Item as NestedObject;
        string property1 = nestedObject.Property1;
        string property2 = nestedObject.Property2;
    }
    return mainObject;
}

Ajax Request

function SendRequest() {
     var mainObject = {
         Id = '1'
     };
     var nestedObject = new NestedObject() {
         Id = '1'
         Property1 = 'A',
         Property2 = 'B'
     };
     mainObject.Item = nestedObject;
     $.ajax({
         url: document.location.origin + '/Test/CreateObject',
         type: 'POST',
         data: {
             mainObject: mainObject
         },
         dataType: 'json',
         success: function() {
             console.log('fine');
         },
         error: function(e) {
             console.log('error');
         },
         complete: () => {
             console.log('complete');
         }
     });
}

StartUp de la web AspNet CORE

En el startup he definido que controle los objetos heredados. Es la propiedad TypeNameHandling.

services.AddMvc()
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
    .AddJsonOptions((options) =>
    {
        options.SerializerSettings.TypeNameHandling = TypeNameHandling.All;
        options.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects;
        options.SerializerSettings.MaxDepth = null;
    });
2
  • En tu class MainObject estas indicando que Item va ser del tipo BaseObject, no NestedObject que es lo que queres recibir, es correcto esto?
    – cjara
    el 7 oct. 2019 a las 14:32
  • @cjara Sí, pq tengo diferentes objetos que heredan de BaseObject. En el controller quiero ver si es de un tipo o de otro para realizar diferentes acciones. Esto en mi WebAPI me devuelve correctamente el objeto heredado, o sea NestedObject. Ahora estoy intentando que tmb funcione en la web y que envie correctamente los datos entre la Web ASP.NET y el cliente javascript para luego enviarlos a la WebAPI.
    – RubenGlam
    el 7 oct. 2019 a las 14:35

1 respuesta 1

0

En principio comentarte que es una muy buena pregunta, ya que es una de estas cosas nunca nos planteamos y existe una alta probabilidad de encontrar un problema así en un entorno productivo real.

Lo que intentas hacer no se puede hacer con el sistema de Binding que trae por defecto ASP.NET Core MVC. Esto es debido a que las estructuras de Modelo polimórficas o con herencia, no son interpretadas por el Binding por defecto.

En tu caso, debes crearte lo se se llama un Model Binder personalizado y aplicarlo al Modelo que quieres interpretar MainObject.

Para esto debes crear las clases personalizadas de Binding, que implementen las Interfaces IModelBinder y IModelBinderProvider. Sería algo así:

public class MyModelBinder : IModelBinder
{
   public Task BindModelAsync(ModelBindingContext bindingContext)
   {
      // Aqui el código de Binding
   }
}

public class MyBinderProvider : IModelBinderProvider
{
    public IModelBinder GetBinder(ModelBinderProviderContext context)
    {
       // Aqui el código de Binding
    }
}

Luego registrárlas como servicios en el Startup.cs:

services.AddMvc(op => op.ModelBinderProviders.Insert(0, new 
MyBinderProvider()));

Y aplicar el nuevo Binder personalizado al Modelo que quieras analizar:

[HttpPost]
public async Task<MainObject> CreateObject([ModelBinder(typeof(MyModelBinder))] MainObject mainObject)
{
    if (mainObject.Item is NestedObject) {
       NestedObject nestedObject = mainObject.Item as NestedObject;
       string property1 = nestedObject.Property1;
       string property2 = nestedObject.Property2;
     }
     return mainObject; 
 }

Este es el trabajo que deberás hacer para solucionar tu problema.

Existen muchos enlaces en Stack Overflow Inglés para este mismo problema, te dejo algunos.

https://stackoverflow.com/questions/46414705/custom-model-binder-in-asp-net-core-for-sub-classes

https://stackoverflow.com/questions/7222533/polymorphic-model-binding

Por otra parte, indicarte también que tienes mal construido el código JavaScript donde construyes los Modelos de datos, realmente no se como te puede funcionar así:

El código correcto sería así:

var mainObject = {
     Id : '1'
 };

 var nestedObject = {
     Id : '1',
     Property1 : 'A',
     Property2 : 'B'
};

 mainObject.Item = nestedObject;

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.