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

为何不同端口的URL在默认设置下可调用ASP.NET Core Web API?

为什么未配置CORS也能跨端口调用Web API?

核心原因很简单:CORS是浏览器专属的安全限制,仅对浏览器发起的跨域请求生效,而你的MVC应用是在服务器端发起的API调用,完全不受浏览器CORS规则约束。

具体拆解:

  • CORS(跨域资源共享)是浏览器为防范恶意网站非法获取其他域名资源而实现的安全策略。只有当请求从浏览器端触发(比如前端JS用fetch、axios发起)时,浏览器才会自动检查跨域规则,发送预检请求或验证响应头中的CORS相关字段。
  • 你的MVC项目里,调用API的代码写在HomeController的Index方法中,是通过RestClient在服务器端发起的HTTP请求。这本质上是服务器与服务器之间的通信,完全绕开了浏览器的CORS限制,只要两个服务网络互通,就能正常调用,和端口是否不同无关。
  • 如果换个场景:在MVC的View页面中用AJAX直接向https://localhost:7254/WeatherForecast发起请求,这时候浏览器就会触发CORS检查,没有配置对应策略的话,就会出现跨域报错。

你的Web API项目Program.cs代码:

using Serilog;

Log.Logger = new LoggerConfiguration()
    .WriteTo.File(
     path: "..\\logs\\log-.txt",
     outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}",
     rollingInterval: RollingInterval.Day,
     restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Information
    )
    .CreateLogger();

var builder = WebApplication.CreateBuilder(args);

builder.Host.UseSerilog();

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

MVC应用HomeController调用代码:

public IActionResult Index()
{
    List<WeatherForecast> list = new List<WeatherForecast>();

    var client = new RestClient("https://localhost:7254");
    var request = new RestRequest("WeatherForecast", Method.Get);

    RestResponse response = client.Execute(request);

    if (response.IsSuccessful && response.Content != null)
    {
        var data = JsonConvert.DeserializeObject<List<WeatherForecast>>(response.Content);

        if (data != null) 
            list = data;
    }

    return View(list);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 02:03:19