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

如何通过安卓浏览器访问Angular本地主机的ASP.NET Web API后端

问题

我是一名新手,正在使用Angular和ASP.NET Web API搭建首个网站。PC浏览器能通过localhost:4200和192.168.100.2:4200访问Web应用,但安卓手机浏览器访问同一本地主机时,登录操作返回服务器错误。

已尝试操作

  • 执行过以下Angular启动命令:
    ng serve --host 192.168.100.2
    ng serve --host 192.168.100.2 --disable-host-check
    ng serve --host 0.0.0.0
    
  • 在Windows Defender防火墙中添加入站规则:
    防火墙规则截图
  • 修改了ASP.NET启动项中的CORS配置

相关代码

Angular组件登录方法

login(){
  if(this.loginForm.valid){
    const record = this.loginForm.getRawValue();
    console.log(record);
    
    this.authService.login({
      username: record.userName,
      password: record.password,
    }).subscribe({
      next:(data: any) => {
        this.authService.authToken = JSON.parse(data).token;
        console.log("Orig Token: ", data);
        console.log("Parsed Token: ", this.authService.authToken);
        console.log("Parsed Token (Subject): ", this.authService.authToken.split('.')[1]);
        console.log("JSON (after atob) ",this.authService.atob);
        console.log("Object (Payload): ",this.authService.payLoad);
        console.log("User id: ",this.authService.userID);
        console.log("Name: ",this.authService.userName);
        console.log("Modules: ",this.authService.accessibleModulesOfUser);

        this.router.navigateByUrl('');
        this.toastr.success("Welcome Back.")
      },
      error: (e) => {
        if (e.status == 0) {
          this.toastr.error("Server is not available. Please try again later")
        }
        else if (e.status == ApiCallStatusCodes.UNAUTHORIZED) {
          this.toastr.error(e.error)
        }
        else {
          this.toastr.error(e.error)
        }
      }
    })
  }
  else{
    this.toastr.warning("Enter username and password.")
  }
}

ASP.NET CORS配置

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseSwagger();
        app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebAPIv5 v1"));
    }

    app.UseHttpsRedirection();

    app.UseRouting();

    app.UseCors(policy => policy.AllowAnyHeader().AllowAnyMethod().WithOrigins("http://localhost:4200", "http://192.168.100.2:4200"));

    app.UseAuthentication();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

解决方案
  1. 确认设备在同一局域网
    检查安卓手机WiFi是否和PC连接到同一个路由器,打开手机浏览器访问http://192.168.100.2:4200,先确保能加载Angular页面,再测试登录。

  2. 修正Angular启动命令
    使用以下命令启动Angular,确保允许所有主机访问且关闭主机检查:

    ng serve --host 0.0.0.0 --port 4200 --disable-host-check
    
  3. 检查API请求地址
    重点检查authService.login调用的API地址,必须是PC的局域网IP(比如http://192.168.100.2:5000/api/xxx),不能用localhost——手机访问localhost会指向自身,导致无法连接到PC上的API服务。

  4. 调整CORS配置
    开发环境可临时放宽CORS规则测试:

    app.UseCors(policy => policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());
    

    测试正常后,再把手机的访问源(http://192.168.100.2:4200)添加回WithOrigins列表,注意协议和端口必须完全匹配。

  5. 验证防火墙规则
    确保防火墙同时开放了Angular的4200端口和ASP.NET API的端口(通常是5000/5001),规则要允许TCP协议,且应用范围覆盖局域网IP段(比如192.168.1.0/24)。

  6. 关闭HTTPS重定向(开发环境)
    如果ASP.NET启用了UseHttpsRedirection,手机浏览器可能因不信任自签名证书导致请求失败,可临时注释该行:

    // app.UseHttpsRedirection();
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 05:50:25