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

Angular调用ASP.NET Core接口报405错误的解决咨询

问题

我正在开发一个与ASP.NET Core后端交互的Angular应用,从Angular调用IsRequestValid端点时收到405 HTTP方法不支持错误,但通过Swagger UI调用同一端点却能正常工作。

Angular服务方法

@Injectable({ providedIn: 'root' })
export class UserAppService {
private apiUrl = '/weatherforecast';

constructor(private http: HttpClient) { }

isRequestValid(input: xxxUserDto): Observable<xxxUserDto> {
const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
return this.http.post<xxxUserDto>(`${this.apiUrl}/IsRequestValid`, input, { headers });
}
}

Angular组件方法

this.userService.isRequestValid(this.UI_User)
.pipe(
catchError((error) => {
this.toaster.error('Fehler beim Validieren des Tokens.');
return throwError(() => error);
})
)
.subscribe((response) => {
this.UI_User = response;
this.setCountDown();
});

后端控制器

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
// Constructor and other methods

    [HttpPost("IsRequestValid")]
    public async Task<ActionResult<xxxUserDto>> IsRequestValid([FromBody] xxxUserDto input)
    {
        // Method implementation
    }

}

Serilog日志输出

2025-03-31 15:54:10.964 +02:00 [INF] Request starting HTTP/1.1 POST https://localhost:52288/weatherforecast/IsRequestValid - application/json 123
2025-03-31 15:54:11.060 +02:00 [INF] Executing endpoint '405 HTTP Method Not Supported'
2025-03-31 15:54:11.064 +02:00 [INF] Executed endpoint '405 HTTP Method Not Supported'

Vite代理错误

15:57:02 [vite] http proxy error: /weatherforecast/IsRequestValid
AggregateError [ECONNREFUSED]:
at internalConnectMultiple (node:net:1139:18)
at afterConnectMultiple (node:net:1712:7)

解决方案

1. 修复Vite代理配置

从代理错误ECONNREFUSED可以看出,Angular的请求未正确转发到后端服务。检查并调整你的vite.config.ts代理配置:

  • 确保目标地址与后端实际运行的URL一致(例如https://localhost:52288)
  • 确认代理规则正确匹配/weatherforecast路径
  • 示例配置:
export default defineConfig({
  server: {
    proxy: {
      '/weatherforecast': {
        target: 'https://localhost:52288',
        changeOrigin: true,
        secure: false // 后端使用自签名证书时需设为false
      }
    }
  }
});

2. 统一路由大小写

ASP.NET Core默认路由大小写敏感,Angular请求的/weatherforecast是全小写,但控制器路由[Route("[controller]")]会生成/WeatherForecast(首字母大写)。可以二选一修改:

  • 将Angular服务中的apiUrl改为'/WeatherForecast'
  • 在后端开启小写路由支持,修改Program.cs:
app.UseRouting();
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers().WithLowerCaseUrls();
});

3. 验证请求参数绑定一致性

确认前后端xxxUserDto的字段结构、命名规则完全匹配(比如避免驼峰/帕斯卡命名差异)。可以在后端方法中添加日志,检查是否接收到请求体:

[HttpPost("IsRequestValid")]
public async Task<ActionResult<xxxUserDto>> IsRequestValid([FromBody] xxxUserDto input)
{
    Log.Information("Received request body: {Input}", JsonSerializer.Serialize(input));
    // 原有业务逻辑
}

4. 完善CORS配置

如果代理未生效,浏览器直接发起跨域请求会触发OPTIONS预检,若后端未配置CORS会导致405错误。在Program.cs中添加CORS配置:

builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowAngular", policy =>
    {
        policy.WithOrigins("http://localhost:5173") // Angular运行地址
              .AllowAnyHeader()
              .AllowAnyMethod();
    });
});

app.UseCors("AllowAngular");

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 14:39:52