ModelBinder.Extension.AspNetCore 1.0.1

dotnet add package ModelBinder.Extension.AspNetCore --version 1.0.1                
NuGet\Install-Package ModelBinder.Extension.AspNetCore -Version 1.0.1                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="ModelBinder.Extension.AspNetCore" Version="1.0.1" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add ModelBinder.Extension.AspNetCore --version 1.0.1                
#r "nuget: ModelBinder.Extension.AspNetCore, 1.0.1"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install ModelBinder.Extension.AspNetCore as a Cake Addin
#addin nuget:?package=ModelBinder.Extension.AspNetCore&version=1.0.1

// Install ModelBinder.Extension.AspNetCore as a Cake Tool
#tool nuget:?package=ModelBinder.Extension.AspNetCore&version=1.0.1                

ModelBinder.Extension.AspNetCore

A simple parameter binding component for ASP.NET Core Web and Web API application.

快速使用

1. 安装

dotnet add package ModelBinder.Extension.AspNetCore

2. 注册

Startup 文件中注册组件,参考 Startup.cs

  • 使用 FromJsonBody
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    ...
        
    app.UseRouting();

    app.UseAuthorization();

    app.UseFromJsonBody(); // should be added before UseEndpoints

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}
  • 使用 FromSmartBody
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
    });
    
	// 方式一:
    //services.AddControllers(options =>
    //{
    //    options.ModelBinderProviders.InsertSmartBodyBinding();
    //});

    // 方式二:
    services.AddControllers().AddSmartBody();
}

3. 使用

3.2 FromJsonBody

示例代码: ValuesController.cs

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    [HttpGet]
    [HttpPost]
    public int Post([FromJsonBody("i1")] int i3, [FromJsonBody] int i2, [FromJsonBody("author.age")] int aAge, [FromJsonBody("author.father.name")] string dadName)
    {
        System.Diagnostics.Debug.WriteLine(aAge);
        System.Diagnostics.Debug.WriteLine(dadName);
        return i3 + i2 + aAge;
    }
}

Postman 请求:

curl --location --request POST 'http://localhost:19623/api/values' \
--header 'Content-Type: application/json' \
--data-raw '{
    "i1":3,
    "i2":2,
    "author": {
        "age": 26,
        "father": {
            "name": "John"
        }
    }
}'
3.2 FromSmartBody

示例代码: Values2Controllercs

[Route("api/[controller]")]
[ApiController]
public class Values2Controller : ControllerBase
{
    [HttpPost]
    public string Post([FromSmartBody("id")] int dadId, [FromSmartBody] string dadName)
    {
        System.Diagnostics.Debug.WriteLine(dadId);
        System.Diagnostics.Debug.WriteLine(dadName);
        return $"{dadId}:{dadName}";
    }
}

Postman 请求:

From query params

curl --location --request POST 'http://localhost:19623/api/values2?id= 3&dadName= 爸爸'

From body form-data:

curl --location --request POST 'http://localhost:19623/api/values2' \
--form 'id=" 3"' \
--form 'dadName=" 爸爸"'

From body x-www-form-urlencoded:

curl --location --request POST 'http://localhost:19623/api/values2' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'id= 3' \
--data-urlencode 'dadName= 爸爸'

From body raw:

curl --location --request POST 'http://localhost:19623/api/values2' \
--header 'Content-Type: application/json' \
--data-raw '{
    "id": 3,
    "dadName": "爸爸"
}'
Binding arrays in query parameters
[Route("api/[controller]")]
[ApiController]
public class Values3Controller : ControllerBase
{
    [HttpGet]
    public string Get([FromSmartBody("dadIds")] int[] ids, [FromSmartBody] IEnumerable<string> hobbies)
    {
        System.Diagnostics.Debug.WriteLine(ids);
        System.Diagnostics.Debug.WriteLine(hobbies);
        return $"{string.Join(",", ids)},爱好:{string.Join("、",hobbies)}";
    }
}

Postman 请求:

curl --location -g --request GET 'http://localhost:19623/api/Values3?dadIds=[1,2,3]&hobbies=["篮球“,"足球","排球"]'

4. 鸣谢

感谢两位 .Net 大佬提供的开源技术和设计思路:

Product Compatible and additional computed target framework versions.
.NET net5.0 is compatible.  net5.0-windows was computed.  net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 is compatible. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 is compatible. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.0.1 4,878 5/28/2022
1.0.0 3,299 5/20/2022

Supports binding arrays in query parameters