局域网设备访问ASP.NET Core7+Angular14应用跳转localhost问题求助
.NET Core 7 + Angular 14 局域网访问重定向至localhost问题
我使用Visual Studio 2022模板创建了.NET Core 7 + Angular 14的Web应用,本地访问正常,但局域网其他设备访问时会被重定向到https://localhost:44417,而客户端设备该端口并未运行服务。我已排查过类似问题,但仍无法解决。
相关配置文件
appsettings.Development.json
{ "AppSettings": { "Token": "DUMMY SECRET KEY" }, "RecaptchaConfig": { "SecretKey": "6LdMYNDUMMYAAFgmSWcLlIk8Fe0sio3xhFKIEWrZ", "ApiUrl": "https://www.google.com/recaptcha/api/siteverify" }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.AspNetCore.SpaProxy": "Information", "Microsoft.Hosting.Lifetime": "Information" } }, "Kestrel": { "Endpoints": { "Http": { "Url": "http://0.0.0.0:5000" }, "Https": { "Url": "https://0.0.0.0:5001" } }, "EndpointDefaults": { "Protocols": "Http1AndHttp2" } }, "ConnectionStrings": { "SqlConnection": "Server=localhost\\SQLEXPRESS;Database=techdocs;Trusted_Connection=True;" }, "Stripe": { "SecretKey": "sk_test_51MikdGKAQ3DDUMMYERnJKwkAWf0lHeE5W0jwfCYnGWocpUlhxzH6xyLymf8gDFoWhfw5EDtQZSRtr5YP9ed00j07KcTHe" } }
launchSettings.json
{ "profiles": { "newTD": { "commandName": "Project", "launchBrowser": true, "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development", "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy" }, "applicationUrl": "https://localhost:7053;http://localhost:5053" }, "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development", "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy" } }, "WSL": { "commandName": "WSL2", "launchBrowser": true, "launchUrl": "https://localhost:7053", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development", "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy", "ASPNETCORE_URLS": "https://localhost:7053;http://localhost:5053" }, "distributionName": "" } }, "iisSettings": { "windowsAuthentication": false, "anonymousAuthentication": true, "iisExpress": { "applicationUrl": "http://localhost:12544", "sslPort": 44317 } } }
Program.cs
global using DataAccess.Data; using DataAccess.DbAccess; using DataAccess.Models; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Hosting; using Microsoft.IdentityModel.Tokens; using Microsoft.OpenApi.Models; //using newTD.Services; using newTD.UserService; using OrdersService; using reCAPTCHA_V3; using Stripe; using Swashbuckle.AspNetCore.Filters; using System.Text; using TemplatesService; using Whois; var builder = WebApplication.CreateBuilder(args); //builder.WebHost.UseUrls("https://0.0.0.0:5001"); StripeConfiguration.ApiKey = builder.Configuration["Stripe:SecretKey"]; builder.Services.AddHttpContextAccessor(); builder.Services.AddHttpClient(); builder.Services.Configure<RecaptchaConfig>(builder.Configuration.GetSection(nameof(RecaptchaConfig))); builder.Services.AddTransient<ISqlDataAccess, SqlDataAccess>(); builder.Services.AddTransient<ITemplateData, TemplateData>(); builder.Services.AddTransient<ITemplateManagement, TemplateManagement>(); builder.Services.AddScoped<IUserData, UserData>(); builder.Services.AddScoped<IUserService, UserService>(); builder.Services.AddTransient<IPricesData, PricesData>(); builder.Services.AddTransient<IOrderData, OrderData>(); builder.Services.AddTransient<ICustomerData, CustomerData>(); builder.Services.AddTransient<IStripeService, StripeService>(); builder.Services.AddScoped<UserModel>(); builder.Services.AddTransient<IWhoisLookup ,WhoisLookup>(); builder.Services.AddTransient<IRecaptchaService, RecaptchaService>(); builder.Services.AddTransient<ICalculateOrderAmount, CalculateOrderAmount>(); builder.Services.AddHttpContextAccessor(); builder.Services.AddControllers(); object value = builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8 .GetBytes(builder.Configuration.GetSection("AppSettings:Token").Value)), ValidateIssuer = false, ValidateAudience = false, RequireExpirationTime = true, ValidateLifetime = true, ClockSkew = TimeSpan.Zero }; }); builder.Services.AddAuthorization(options => { options.AddPolicy("FullAccessForAdminRole", policy => policy.RequireRole("admin")); }); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(options => { options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme { Description = "Standard Authorization header using the Bearer scheme (\"bearer {token}\")", In = ParameterLocation.Header, Name = "Authorization", Type = SecuritySchemeType.ApiKey }); options.OperationFilter<SecurityRequirementsOperationFilter>(); }); var AllowStripeCORS = "AllowStripeCORS"; builder.Services.AddCors(options => { options.AddPolicy(name: AllowStripeCORS, policy => { policy.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod(); //policy.WithOrigins("https://checkout.stripe.com").AllowAnyHeader().AllowAnyMethod(); //.SetIsOriginAllowedToAllowWildcardSubdomains(); }); }); var app = builder.Build(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { //app.UseSwagger(x => x.SerializeAsV2 = true); //app.UseSwaggerUI( // c => // { // c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); // c.RoutePrefix = ""; // }); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseCors(AllowStripeCORS); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); app.Run();
解决方案
问题根源
重定向到localhost的核心原因是应用绑定地址限制、SpaProxy转发配置、Angular开发服务器监听范围三者的不匹配:
- launchSettings中仅绑定localhost,导致Kestrel未监听局域网IP;
- Angular开发服务器默认只接受localhost请求,SpaProxy转发时会强制返回localhost地址;
- Https重定向规则未适配局域网访问场景。
修复步骤
修改launchSettings.json,开放局域网绑定
更新newTD和WSL配置的地址,同时绑定0.0.0.0和localhost,既支持局域网访问也保留本地开发便利性:"newTD": { "commandName": "Project", "launchBrowser": true, "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development", "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy" }, "applicationUrl": "https://0.0.0.0:7053;http://0.0.0.0:5053;https://localhost:7053;http://localhost:5053" }, "WSL": { "commandName": "WSL2", "launchBrowser": true, "launchUrl": "https://localhost:7053", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development", "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy", "ASPNETCORE_URLS": "https://0.0.0.0:7053;http://0.0.0.0:5053;https://localhost:7053;http://localhost:5053" }, "distributionName": "" }配置Angular开发服务器允许局域网访问
找到Angular项目根目录的angular.json,修改serve配置的options,添加监听全地址和关闭主机检查(仅开发环境使用):"serve": { "builder": "@angular-devkit/build-angular:dev-server", "options": { "browserTarget": "your-project-name:build", "host": "0.0.0.0", "disableHostCheck": true } }调整Https重定向规则(可选)
若局域网设备访问http时重定向异常,可在开发环境临时关闭Https重定向,或指定正确的端口:// 开发环境关闭Https重定向 if (!app.Environment.IsDevelopment()) { app.UseHsts(); app.UseHttpsRedirection(); } // 或指定重定向端口 app.UseHttpsRedirection(options => { options.HttpsPort = 7053; });开放防火墙端口
在Windows防火墙中开放5053(HTTP)、7053(HTTPS)端口,允许局域网设备的入站请求。
验证方式
启动应用后,在局域网设备上访问http://[服务器IP]:5053或https://[服务器IP]:7053,确认不再重定向到localhost。
内容的提问来源于stack exchange,提问作者A B
相关产品推荐
相关产品推荐

