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

本地WebAPI启用PUT/DELETE方法遇问题:直接请求返回405错误

405错误排查:直接访问Delete接口失败但Swagger正常

问题场景

我编写的EmployeeController代码如下:

[ApiController]
[Route("[controller]")]
public class EmployeeController : ControllerBase
{
    [HttpGet("[action]/")]
    public async Task<IActionResult> GetAll()
    {
        return Ok(await _employeeService.GetAllEmployees());
    }
    [HttpDelete("[action]/{id}")]
    public async Task<IActionResult> Delete(int id)
    {
        await _employeeService.DeleteEmployee(id);
        return Ok();
    }
}

通过Swagger调用所有接口都正常,但直接访问https://localhost:7080/Employee/Delete/3时返回405错误。查资料发现这类问题多出现于已部署的API,但本地环境也遇到了,请问可能缺少什么配置?

补充:我也尝试用TypeScript发送请求,代码如下:

async function deleteById(url: string, id: number) {
    return await fetch(url + id.toString(), { method: 'DELETE', }).then((response) => {
        if (!response.ok)
            console.log(response);
        else
            return response.json();
    });
}
deleteById("https://localhost:7080/Employee/Delete/", id).then((json) => {
        console.log(json);
    });

请求后仍返回405错误(截图显示405 Method Not Allowed)

可能的原因及解决方法

  • 路由后缀斜杠不匹配:HttpDelete的路由定义是[action]/{id},但请求URL中Delete后多了一个斜杠,导致路由匹配失败。ASP.NET Core会尝试用不支持的请求方法处理,最终返回405。
    解决:要么修改路由定义为[HttpDelete("[action]/{id}/")](添加后缀斜杠),要么去掉请求URL中Delete后的斜杠,比如TS代码中把请求地址改为"https://localhost:7080/Employee/Delete",拼接id后形成正确路径Employee/Delete/3。

  • 跨域(CORS)配置缺失:前端跨域请求时,浏览器会先发送OPTIONS预检请求,如果API未配置CORS,预检请求失败会返回405。而Swagger属于同域请求,不受影响。
    解决:在Program.cs中添加CORS配置:

    builder.Services.AddCors(options =>
    {
        options.AddPolicy("AllowAll", policy =>
        {
            policy.AllowAnyOrigin()
                  .AllowAnyMethod()
                  .AllowAnyHeader();
        });
    });
    
    // 注意UseCors要放在UseRouting之后、UseAuthorization之前
    app.UseCors("AllowAll");
    
  • WebDAV模块拦截请求:本地IIS Express默认启用的WebDAV模块会拦截DELETE请求,导致返回405。
    解决:在项目的web.config中禁用WebDAV:

    <system.webServer>
      <modules runAllManagedModulesForAllRequests="true">
        <remove name="WebDAVModule" />
      </modules>
      <handlers>
        <remove name="WebDAV" />
      </handlers>
    </system.webServer>
    
  • 路由冲突:如果存在其他控制器或Action的路由与Employee/Delete/{id}匹配,会导致请求被错误路由,返回405。
    解决:检查项目中所有路由定义,确保没有路由冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 14:24:17