【问题标题】:Cannot call DELETE webapi method due to 405 Http status code由于 405 Http 状态码,无法调用 DELETE webapi 方法
【发布时间】:2019-08-24 17:42:13
【问题描述】:

我使用 .NET Core 3.0 Preview 编写了 API,并使用 Angular 8 作为前端。 我在用户控制器上有一种名为 DeleteUser 的方法。方法是这样的:

//DELETE users/d18da620-6e4d-4b1c-a1ec-36d89145f4ca
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteUser(Guid id) {
    ...
}

所以,当请求像这样使用 Angular 执行时:

this.usersApiService.deleteUser(userId).subscribe((data) => {
    ...
}

执行此调用后,我在 Visual Studio 中得到以下输出:

Microsoft.AspNetCore.Cors.Infrastructure.CorsService:Information: CORS policy execution successful.
Microsoft.AspNetCore.Routing.EndpointMiddleware:Information: Executing endpoint '405 HTTP Method Not Supported'

但是,我设置了自定义 CORS 政策。在ConfigureServices 我有这个:

services.AddCors(options => {
    options.AddPolicy("CorsPolicy",
        builder => builder
            .AllowAnyMethod()
            .AllowCredentials()
            .SetIsOriginAllowed((host) => true)
            .AllowAnyHeader());
});

在配置方法中,我使用这个策略:

app.UseCors("CorsPolicy");

所以我的问题是,如何成功调用这个删除方法?我错过了什么?

编辑:这是我调用 api 的 deleteUser 方法

public deleteUser(userId) {
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type' : 'application/json'
      }),
      body: {
        id: userId
      }
    };
    return this.httpClient.delete(this.USERSENDPOINT, httpOptions);
}

【问题讨论】:

  • 你能提供usersApiService.deleteUser代码吗?
  • @Nikita,哦,是的,我在那里粘贴了错误的代码 :) 谢谢。将其添加到我的问题中
  • 按照规范,DELETE 调用中不能有正文。 URL 必须定义要删除的资源。

标签: asp.net-core asp.net-core-webapi


【解决方案1】:

更新: 尝试像这样以角度调用您的方法:

this.httpClient.delete(this.USERSENDPOINT+"/"+userId);

希望对你有帮助

【讨论】:

  • 使用此配置,我收到以下错误:HTTP Error 500.19 - Internal Server Error The configuration section 'httpProtocol' cannot be read because it is missing a section declaration
  • 不,它不在system.webServer element 中。但是,将其添加到 web.config 后,现在我无法对整个集合执行基本 Get 事件(例如:GET /users
  • JS控制台报错说CORS header Access-Control-Allow-Origin不匹配localhost:4200
  • 删除请求中的正文在哪里?
  • 我相信问题出在 Angular 而不是 .NET 中……我现在才想到这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-15
  • 1970-01-01
  • 1970-01-01
  • 2019-03-05
  • 2017-06-15
  • 2011-07-19
相关资源
最近更新 更多