在ASP.NET Core 6.0版本中,使用Minimal API可以轻松地将JSON请求正文绑定到所需的类。可以使用以下代码示例:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Text.Json;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var app = builder.Build();
// 绑定POST请求的JSON正文到指定的类
app.MapPost("/api/SomeEndpoint", async context =>
{
var requestObject = await JsonSerializer.DeserializeAsync(context.Request.Body);
// 执行类中的相关操作
var response = new ResponseClass();
// ...
// 返回JSON响应
var jsonResponse = JsonSerializer.Serialize(response);
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(jsonResponse);
});
app.Run();
在上面的示例代码中,我们向应用程序的“/api/SomeEndpoint”端点发送POST请求,并绑定请求正文到名为“RequestClass”的类对象中。然后我们在类中执行所需的操作,并将结果绑定到名为“ResponseClass”的类对象中。最后,我们将响应序列化为JSON,并发送回客户端。