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

Asp.net core 3.1 Web API中HttpPost请求返回405 Not Allowed怎么解决

问题根因
  • 核心原因是当前VideoWallController中定义了2个没有指定差异化路由的[HttpPost]方法,ASP.NET Core路由系统无法区分请求应该匹配哪个POST端点,导致返回405状态码,和CORS配置无关,Postman本地调用不会触发CORS校验,你之前调整CORS配置无法解决问题。
  • 次要问题:teststring方法的string test参数没有添加[FromBody]特性,即使路由正常,发送raw文本格式的请求也会出现参数绑定失败的问题。
解决方案
  1. 给两个POST方法添加差异化路由后缀,避免路由匹配冲突,修改后的控制器核心代码如下:
[Route("api/[controller]")]
[ApiController]
public class VideoWallController : ControllerBase
{
    // GET: api/<ValuesController>
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/<ValuesController>/5
    [HttpGet("{id}")]
    public string Get(int id)
    {
        return "value";
    }

    // 路由为POST api/VideoWall/prova
    [HttpPost("prova")]
    public string prova([FromBody] VideoCallBack test)
    {
        return "true;";
    }

    // 路由为POST api/VideoWall/teststring,补充FromBody特性适配raw格式参数绑定
    [HttpPost("teststring")]
    public void teststring([FromBody] string test)
    {

    }

    // PUT api/<ValuesController>/5
    [HttpPut("{id}")]
    public void Put(int id, [FromBody] string value)
    {
    }

    // DELETE api/<ValuesController>/5
    [HttpDelete("{id}")]
    public void Delete(int id)
    {
    }
}
  1. 调整Postman请求路径:
  • 如果要调用prova方法,请求地址改为{你的服务地址}/api/VideoWall/prova,请求体传入符合VideoCallBack结构的JSON数据。
  • 如果要调用teststring方法,请求地址改为{你的服务地址}/api/VideoWall/teststring,raw格式选JSON,请求体直接传入带引号的字符串值即可,例如"测试内容"。
  1. (可选CORS配置规范)如果后续需要支持跨域调用,确保中间件顺序正确,CORS配置必须放在UseRouting之后、UseAuthorization之前:
// ConfigureServices中注册
services.AddCors(options => 
{
    options.AddPolicy("AllowAll", policy => 
    {
        policy.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
    });
});

// Configure中按顺序配置
app.UseRouting();
app.UseCors("AllowAll"); // 必须在Routing之后,Authorization之前
app.UseAuthorization();

内容的提问来源于stack exchange,提问作者Antonio Di Girolamo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 23:30:01