I just converted a project to .net core and one of the changes is that I can now only have 1 [FromBody] attribute passed to a controller action. Previously I was passing in a JSON object into the body like so:
{
property1: 1,
property2: 2
}
and could receive those 2 properties in the controller like so:
public doSomething([FromBody]int property1, [FromBody]int property2)
now I have to create a new class for the parameters that get passed in through the body:
public class DoSomethingParams {
public int property1;
public int property2;
}
public doSomething([FromBody]DoSomethingParams bodyParams)
This creates a whole lot more code, especially when I have to pass in 10 or more parameters for a call, and it feels very inefficient to me.
In Javascript there are destructuring operations that I could use one aforementioned object like this: let property1 = {property1};
. Is there any similar alternative in C#? I read about tuple deconstructing in C# v7 but I'm not quite sure that it helps me here (eg. adding [FromBody](int property1, int property2)
as an argument doesn't work. (Identifier expected error))
Is there a more efficient way to deconstruct the JSON object I'm passing in besides creating a class skeleton for it? Thanks for the help!
You need to create a custom model provider to achieve that. check this package it does just that: https://github.com/m6t/M6T.Core.TupleModelBinder
You just need to add the custom binder to your binder providers at the first position:
services.AddMvc(options =>
{
options.ModelBinderProviders.Insert(0, new TupleModelBinderProvider());
})
and then you will be able to use the Tuple deconstruct:
public doSomething((int property1, int property2, string other) bodyParams) {
// bodyParams.property1
// bodyParams.property2
// bodyParams.other
}
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.