Asp.net Core 3.1 Web api 请求,其中包含未绑定的对象数组



我有一个 ASP.net Core 3.1 Web api项目。在我的一个控制器中,我有一个 Post 方法,该方法接受包含对象数组的请求对象。我在 ASP.Net 使用.Net Framework和 ASP.Net Core 2.1中做了同样的事情,没有问题。但是,在 3.1 中,调用 api 方法时数组未绑定。

[HttpPost(), Route("{id}/Answers")]
[ProducesResponseType(typeof(QuestionaireAnswerModel), StatusCodes.Status201Created)]
public async Task<IActionResult> PostAnswers(int id, QuestionaireAnswerRequestModel request) {
try
{
if (ModelState.IsValid)
{
if (request.Answers == null || request.Answers.Count < 1) 
return BadRequest("Answers are required.");
var result = await _service.CreateQuestionaireAnswersAsync(id, request);
return Created($"https://blah/api/{result.Id}", result);
}
else { return BadRequest(ModelState); }
}
catch (Exception ex)
{
var message = $"An error occurred posting answers for Questionnaire. Questionnaire Id: {id}, UserName: {request.UserName}";
_logger.LogError(ex, message);
return StatusCode(StatusCodes.Status500InternalServerError, message);
}
}

C# 模型

public class QuestionaireAnswerRequestModel
{
public string UserName { get; set; }
public IEnumerable<QuestionAnswerRequestModel> Answers;
}
public class QuestionAnswerRequestModel
{
public int QuestionId { get; set; }
public bool Answer { get; set; }
}

邮递员用于测试的示例请求 {

"userName": "testuser",
"answers": [{
"questionId": 1,
"answer": "false"
}]

}

尝试调试时,答案列表始终为 null。我尝试使用数组和列表类型而不是 IEnumerable,但没有运气。我知道他们在 3.1 中更改了序列化程序,但不确定为什么数组无法序列化?有谁知道答案? 这是我的创业公司.cs

public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{            
var connection = Configuration.GetConnectionString("HealthScreeningConnection");
services.AddEntityFrameworkSqlServer()
.AddEntityFrameworkProxies()
.AddDbContextPool<HealthScreeningContext>((serviceProvider, options) => {
options.UseSqlServer(connection).UseInternalServiceProvider(serviceProvider);
options.UseLazyLoadingProxies();
});
services.AddScoped<IQuestionareService, QuestionaireService>();
services.AddScoped<IAccountService, AccountService>();
services.AddControllers();
services.AddCors(opts => {
opts.AddPolicy("CorsPolicy", builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
var nlogFilePath = "nlog.config";
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
nlogFilePath = $"nlog.{env.EnvironmentName}.config";
}
NLog.LogManager.LoadConfiguration(nlogFilePath);
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseCors("CorsPolicy");
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}

我认为您需要使 QuestionaireAnswerRequestModel 字段 Answers 是一个属性,例如。 添加 { get; set; } 到它:

public class QuestionaireAnswerRequestModel
{
public string UserName { get; set; }
public IEnumerable<QuestionAnswerRequestModel> Answers { get; set; }
}

从 MSDN:

复杂类型必须具有要绑定的公共默认构造函数和公共可写属性。发生模型绑定时,将使用公共默认构造函数实例化类。

苏尔斯:https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-3.1

最新更新