You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用Controller中POST接口返回Bad Request问题排查求助

问题:调用POST接口始终返回Bad Request状态码

使用Http.PostJsonAsync调用Controller的POST方法时,一直返回Bad Request,但其他结构完全一致(仅模型和名称不同)的Controller可以正常工作,求排查问题。

调用代码

private async Task AddAdditionalItem(string valueTest1, string valueDateTest1)
{
    article_list inputSQL = new article_list();
    inputSQL.articlename = valueTest1;
    inputSQL.date = valueDateTest1;

    var x = await Http.PostJsonAsync(baseUrl + "/api/article_list/create", inputSQL);
    Console.WriteLine(x.StatusCode);
}

Controller代码

[Route("api/[controller]")]
[ApiController]
public class article_list_Controller : ControllerBase
{
    private readonly SqlDbContext_test _dbContext;

    public article_list_Controller(SqlDbContext_test dbContext)
    {
      _dbContext = dbContext;
    }

    [HttpPost]
    [Route("Create")]
    public async Task<bool> Create([FromBody] article_list article)
    {
        Console.WriteLine("Create");
        
        if(ModelState.IsValid){

            _dbContext.Add(article);
            try
            {
                await _dbContext.SaveChangesAsync();
                return true;
            }
            catch (DbUpdateException)
            {
                return false;
            }
        }
    }
}

数据库上下文类

public class SqlDbContext_test : DbContext
{
    public SqlDbContext_test(DbContextOptions<SqlDbContext_test> options) : base(options)
    {
    }
    public DbSet<article_list> article_list {get;set;}

    protected override void OnModelCreating(ModelBuilder modelbuilder){
        modelbuilder.Entity<article_list>().HasNoKey();
    }
}

模型类

public class article_list
{
    #nullable enable
    public string? articlename 
    { 
        get; 
        set; 
    }
    public string? date 
    { 
        get; 
        set; 
    }
}

自定义HttpClient方法

public async Task<HttpResponseMessage> PostJsonAsync<T>(string requestUri, T content)
{
    HttpClientHandler clientHandler = new HttpClientHandler();
    clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };

    // Pass the handler to httpclient(from you are calling api)
    HttpClient httpClient = new HttpClient(clientHandler);
    string myContent = JsonConvert.SerializeObject(content);
    StringContent stringContent = new StringContent(myContent, Encoding.UTF8, "application/json");
    var response = await httpClient.PostAsync(requestUri, stringContent);
    httpClient.Dispose();
    return response;
}

排查方向

  • 路由匹配错误:ASP.NET Core中,[controller]会自动去掉控制器类名的Controller后缀。你的控制器类名为article_list_Controller,实际路由前缀是/api/article_list_,但你调用的是/api/article_list/create,路由不匹配导致400错误。解决方法:要么修改控制器类名为article_listController(去掉下划线),要么修改路由属性为[Route("api/article_list")],或者调整调用URL为/api/article_list_/create。
  • ModelState验证失败:当前Controller中ModelState.IsValid不满足时无响应返回,[ApiController]特性会自动返回Bad Request。可以修改Controller方法,在验证失败时返回详细错误信息:
    if(ModelState.IsValid){
        // 原有逻辑
    }
    return BadRequest(ModelState); // 添加此行
    
    然后在客户端打印响应内容,即可看到具体验证错误。
  • 检查请求内容:确认valueTest1和valueDateTest1是否为有效数据,也可在自定义HttpClient中打印序列化后的JSON,确认格式是否符合接口要求。

内容的提问来源于stack exchange,提问作者J.Doe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 15:30:43