Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding Multiple Parameters in an HTTP POST Request in ASP.NET Core .NET 6

I'm encountering a challenge while migrating from ASP.NET MVC "classic" to ASP.NET Core with .NET 6.

In the past (ASP.Net MCV 4, ... 5), I could easily handle multiple parameters in an HTTP POST request, like this:

public ActionResult MyAction(MyComplexModel MyModel, bool isCompliant)

However, with ASP.Net Core (.Net 6.0), I'm facing difficulties in handling multiple parameters in the method signature. I've tried various solutions, including optional parameters, but so far, I haven't been able to achieve parameter binding as I expected.

My main issue is that I have a complex object, for example, MyComplexModel, and I'd like to pass a boolean parameter isCompliant without modify the model or having to create a new ViewModel or use a wrapper for every possible combination of parameters. It seems absurd to have to generate a different ViewModel each time just to change the number and types of aggregated data. Furthermore, in the "classic" MVC approach, it was sufficient for the parameters sent via JSON to match in number and type with those in the method signature, and the variables were automatically populated with the correct casts.

Currently, I've resolved the situation by using a single ViewModel that can handle various parameter combinations. Here's an example of how I manage it:

public class MyUnifiedViewModel
{
public MyComplexModel MyModel { get; set; }
public bool IsCompliant { get; set; }
}

[HttpPost]
 public IActionResult MyAction([FromBody] MyUnifiedViewModel viewModel)
 {
    // Now, I can access viewModel.MyModel and viewModel.IsCompliant
    // ...

   return Ok("Operation completed successfully.");
  }

I'm seeking your assistance and advice on how to tackle this situation more efficiently in ASP.NetCore 6, avoiding the creation of specific ViewModels for every possible parameter combination. What are the best practices or recommended approaches for handling multiple parameters in ASP.Net Core?

Thank you in advance for your support.

like image 451
treep Avatar asked Mar 03 '26 08:03

treep


1 Answers

If you send the isCompliant together with other property in json

you may need a custom model binder :

public class MyBinder : IModelBinder
 {
     public Task BindModelAsync(ModelBindingContext bindingContext)
     {
         var modelName = bindingContext.FieldName;
         var body = bindingContext.HttpContext.Request.Body;
         body.Position = 0;
         using StreamReader reader = new StreamReader(body, Encoding.UTF8, true, 1024, true);
         var str=reader.ReadToEnd();
         JObject jsonObject = JObject.Parse(str);
         var existproperty=jsonObject.TryGetValue(modelName, out var val);
         if (existproperty)
         {  
             //you have to modify the codes here,I would modify the codes here when I have free time
             var result=val?.ToString()=="True"?true:false;
             bindingContext.Result = ModelBindingResult.Success(result);
         }
         return Task.CompletedTask;
     }
 }

Enable request body be read mutiple times before first read(in my case,I tried with a middleware)

app.Use(async (httpcontext, next) =>
{
    httpcontext.Request.EnableBuffering();
    await next.Invoke();
});

apply the binder:

[ModelBinder(typeof(MyBinder))]bool? IsCompliant

Now it was bind successfully:

enter image description here

like image 169
Ruikai Feng Avatar answered Mar 05 '26 04:03

Ruikai Feng