.EnCore MVC deserialization

In a .netcore application, I would suggest the following (simplified):

// Create a new record, assume it returns an ID=1
https://site/MyController/Save?FirstName=John&LastName=Doe&Status=Active

// Update the record without full state
PUT https://site/MyController/1
{
  'DOB': '1/1/1970',
  'Status': null
}

I would like to translate this second call to:

UPDATE MyModel SET DOB = '1/1/1970' AND Status=NULL WHERE Id = 1

I can, of course, encode my method Createin MyControllerto parse the query (querystring / form / body) for the presented values ​​and create my SQL accordingly.

However, I would rather follow the MVC conventions and use the binding that MVC offers out of the box:

public async Task<MyModel> Save(string id, [FromBody]MyModel instance)
{
  await _MyRepository.UpdateAsync(id, message);
  return message;
}

The problem is that the instance will look like this:

{
  'FirstName': null,
  'LastName': null,
  'DOB': '1/1/1970',
  'Status': null
}

At what point can I not determine which fields should be NULLED in Db, and which should be left alone.

I implemented a wrapper class that:

  • upon deserialization, sets any dirty properties and
  • after serialization, records only dirty properties

, :

public async Task<MyModel> Save(string id, [FromBody]MyWrapper<MyModel> wrapper
{
  await _MyRepository.UpdateAsync(id, wrapper.Instance, wrapper.DirtyProperties);
  return wrapper.Instance;
}

:

  • ?
  • MVC ()?
+4
2

.

  • : , IModelBinder:

    /// <summary>
    /// Defines an interface for model binders.
    /// </summary>
    public interface IModelBinder
    {
       /// <summary>
       /// Attempts to bind a model.
       /// </summary>
       /// <param name="bindingContext">The <see cref="ModelBindingContext"/>.</param>
       /// <returns>
       /// <para>
       /// A <see cref="Task"/> which will complete when the model binding process completes.
       /// </para>
       /// <para>
       /// If model binding was successful, the <see cref="ModelBindingContext.Result"/> should have
       /// <see cref="ModelBindingResult.IsModelSet"/> set to <c>true</c>.
       /// </para>
       /// <para>
       /// A model binder that completes successfully should set <see cref="ModelBindingContext.Result"/> to
       /// a value returned from <see cref="ModelBindingResult.Success"/>. 
       /// </para>
       /// </returns>
       Task BindModelAsync(ModelBindingContext bindingContext);
     }
    
  • :

    services.AddMvc().Services.Configure<MvcOptions>(options => {
        options.ModelBinders.Insert(0, new YourCustomModelBinder());
    });
    

MVC github repo " :

+1

PUT , HTTP PATCH . , , , JSONPatchDocument, , .

0

Source: https://habr.com/ru/post/1667671/


All Articles