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

从MinimalApi实例向MVC实例发送请求的异常问题排查

问题:MinimalApi调用MVC控制器时的请求异常

我正在创建一个对外可访问的MinimalApi服务,需要向MVC控制器服务发送GET/POST/PUT请求,但遇到以下问题:

  • 发送GET请求时,明明控制器方法必然返回BadRequest,却收到200(OK)状态码,推测请求未实际发送到MVC控制器
  • 发送POST或PUT请求时,收到405(Method Not Allowed)状态码

已在两端配置CORS,但问题仍未解决。

MinimalApi示例代码

app.MapGet("/SendTestRequest", async (HttpClient httpClient) =>
{
    HttpRequestMessage httpRequestMessage = new() 
    { 
        RequestUri = new Uri($"https://localhost:44313/TestNotification/SendTestRequest"), 
        Method = HttpMethod.Get
    };
    HttpResponseMessage result = await httpClient.SendAsync(httpRequestMessage);
    result.EnsureSuccessStatusCode();
});

MVC控制器示例代码

[EnableCors("cors")]
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> SendTestRequest()
{
    return BadRequest();  
}

MinimalApi端CORS配置

// Program.cs
builder.Services.AddHttpClient();
builder.Services.AddCors(options =>
{
    options.AddPolicy(name: "cors",
        policy =>
        {
            policy.AllowAnyOrigin();
            policy.AllowAnyMethod();
        });
});

app.UseCors("cors");

MVC端CORS配置

// ConfigureServices 部分
services.AddCors(options =>
{
    options.AddPolicy(name: "cors",
        policy =>
        {
            policy.AllowAnyOrigin();
            policy.AllowAnyMethod();
            policy.AllowAnyHeader().WithExposedHeaders("*");
        });
});

// Configure 部分
app.UseCors("cors");

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 20:20:48