为何不同端口的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
相关产品推荐
相关产品推荐

