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

.NET 8 Web API单个控制器PUT/DELETE/POST请求报405错误

405 Method Not Allowed 问题排查与解决

常见原因及排查方向

  • WebDAV模块拦截:ASP.NET默认启用的WebDAV模块会拦截PUT/DELETE请求,这是此类问题的高发原因。
  • 路由配置不匹配:控制器的路由模板、HTTP方法特性标记可能存在错误,导致请求无法匹配到对应方法。
  • 跨域策略遗漏:全局跨域配置可能未覆盖该控制器的路由,或未明确允许PUT/DELETE/POST方法。
  • 前后端参数/请求格式不匹配:Angular请求的URL、参数、Content-Type与后端控制器方法签名不对应。

针对配置代码的逐一排查

1. Web.Config 禁用WebDAV

在system.webServer节点下添加或确认以下配置,移除WebDAV模块和处理器:

<system.webServer>
  <modules runAllManagedModulesForAllRequests="true">
    <remove name="WebDAVModule" />
  </modules>
  <handlers>
    <remove name="WebDAV" />
  </handlers>
</system.webServer>

2. Startup.cs 跨域配置验证

确保跨域策略包含所有需要的HTTP方法,且启用位置正确:

services.AddCors(options =>
{
    options.AddPolicy("AllowAll", policy =>
    {
        policy.AllowAnyOrigin()
              .AllowAnyHeader()
              .AllowAnyMethod(); // 或明确指定:.WithMethods("GET", "POST", "PUT", "DELETE")
    });
});

// 注意顺序:在UseRouting之后、UseAuthorization之前启用CORS
app.UseRouting();
app.UseCors("AllowAll");
app.UseAuthorization();

3. 控制器代码检查

确认控制器及方法的路由、HTTP特性标记正确:

[ApiController]
[Route("api/[controller]")]
public class ListTableController : ControllerBase
{
    [HttpPost]
    public IActionResult Create([FromBody] ListTableModel model)
    {
        // 业务逻辑
        return Ok();
    }

    [HttpPut("{id:int}")]
    public IActionResult Update(int id, [FromBody] ListTableModel model)
    {
        // 业务逻辑
        return Ok();
    }

    [HttpDelete("{id:int}")]
    public IActionResult Delete(int id)
    {
        // 业务逻辑
        return Ok();
    }
}
  • 检查HTTP特性拼写(如HttpPut而非HttpGet)
  • 确认路由参数(如{id:int})与请求URL中的参数类型匹配

4. Angular服务代码验证

检查请求URL、方法及格式是否与后端匹配:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { ListTableModel } from './models';

@Injectable({ providedIn: 'root' })
export class ListTableService {
  private baseUrl = '/api/ListTable';

  constructor(private http: HttpClient) {}

  createItem(model: ListTableModel) {
    return this.http.post(this.baseUrl, model);
  }

  updateItem(id: number, model: ListTableModel) {
    return this.http.put(`${this.baseUrl}/${id}`, model);
  }

  deleteItem(id: number) {
    return this.http.delete(`${this.baseUrl}/${id}`);
  }
}
  • 核对请求URL是否与控制器路由完全一致(避免多/少斜杠、大小写不匹配)
  • 查看浏览器Network面板,确认请求的实际方法、URL及响应头信息

额外验证步骤

  • 用Postman直接调用后端接口,排除Angular端的问题
  • 查看服务器日志,获取更详细的错误上下文
  • 确认控制器类名与路由模板匹配(ListTableController对应api/ListTable)

内容的提问来源于stack exchange,提问作者whebz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 12:07:39