簡體   English   中英

Asp.net Core 3.1 Web api 對象數組請求未綁定

[英]Asp.net Core 3.1 Web api request with array of objects not binding

我有一個 ASP.net Core 3.1 web api 項目。 在我的一個控制器中,我有一個 Post 方法,它接受包含對象數組的請求 object。 我在 ASP.Net using.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; }
    }

示例請求在 postman 中用於測試 {

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

}

嘗試調試,答案列表始終為 null。我嘗試使用數組和列表類型而不是 IEnumerable,但沒有成功。 我知道他們在 3.1 中更改了序列化程序,但不確定為什么數組無法序列化? 有人知道答案嗎? 這是我的 startup.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 設為一個屬性,例如。 添加{得到; 放; } 對它:

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

來自 MSDN:

復雜類型必須具有公共默認構造函數和要綁定的公共可寫屬性。 當 model 發生綁定時,使用公共默認構造函數實例化 class。

來源: https://learn.microsoft.com/en-us/as.net/core/mvc/models/model-binding?view=as.netcore-3.1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM