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

ASP.NET Core 6中CORS跨域功能异常求助

ASP.NET Core 6 Web API 局域网客户端请求失败排查

问题描述

使用ASP.NET Core 6开发Web API,局域网内本地Postman及Windows Form客户端测试正常,但其他电脑的相同客户端请求失败。相关代码如下:

Program.cs 代码

var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();

builder.Services.AddCors(options =>
{
    options.AddPolicy(name: MyAllowSpecificOrigins,
                      policy =>
                      {
//192.168.100.60是另一台电脑的IP                         
policy.WithOrigins("https://192.168.100.60:7214/api/Email")     
                                              .AllowAnyOrigin()
                                              .AllowAnyHeader()
                                              .AllowAnyMethod();

                      });
});

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
   
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseCors(MyAllowSpecificOrigins);

app.UseAuthorization();

app.MapRazorPages();

app.MapControllers();

app.Run();

API控制器代码

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace PracticeAPI2
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmailController : ControllerBase
    {
        [HttpPost]
        public async Task<IActionResult> SendEmail([FromBody] EmailRequest request)  
        {
            // 可在此添加邮件处理逻辑
            // 示例仅返回成功响应
            await Task.Delay(100); // 模拟异步处理
            string email = request.Email;
            return Ok(new { Success = true, Message = "Email received and processed successfully." }); 

        }

    }
}
namespace PracticeAPI2
{
    public class EmailRequest
    {
        private string email = ""; 
        public string Email { get => email; set => email = value ?? ""; }
    }
}

Windows Form客户端代码

using System.Net;
using System.Text;
using System.Text.Json;

namespace Practice_UI
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        async Task<bool> SendEmailToApi(string email)    
        {
            try
            {

                using (HttpClient client = new HttpClient())    
                {
                                                               
                    var json = new
                    {
                        email
                    };


                    string jsonEmail = JsonSerializer.Serialize(json);  

                    var content = new StringContent(jsonEmail, Encoding.UTF8, "application/json");
                    string apiUrl = "https://192.168.100.60:7214/api/Email"; 

                    HttpResponseMessage response = await client.PostAsync(apiUrl, content);

                    if (response.IsSuccessStatusCode)
                    {
                        return true;
                    }
                    else
                    {
                        string statusCode = response.StatusCode.ToString();
                        MessageBox.Show($"API請求失敗,狀態碼:{statusCode}", "API Request Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return false;

                    }
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show($"錯誤:{ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            string email = txtEmail.Text;

            if (!string.IsNullOrWhiteSpace(email))
            {
                bool success = await SendEmailToApi(email);
                if (success)
                {
                    lblStatus.Text = "Email sent successfully!";
                    lblStatus.ForeColor = Color.Green;
                }
                else
                {
                    lblStatus.Text = "Failed to send email.";
                    lblStatus.ForeColor = Color.Red;
                }
            }
            else
            {
                lblStatus.Text = "Please enter a valid email.";
                lblStatus.ForeColor = Color.Red;
            }
        }
    }
}

问题排查与修复

1. CORS配置修正(非桌面客户端失败核心原因)

  • 错误点:WithOrigins填写API自身地址而非客户端来源,且AllowAnyOrigin()会覆盖前置规则,导致配置无效。
  • 补充说明:Windows Form等桌面客户端不属于浏览器环境,不会触发CORS校验,此配置错误并非请求失败核心原因,但需规范配置:
builder.Services.AddCors(options =>
{
    options.AddPolicy(name: MyAllowSpecificOrigins,
                      policy =>
                      {
                          // 开发环境临时允许所有来源(生产环境请指定具体客户端IP/域名)
                          policy.AllowAnyOrigin()
                                .AllowAnyHeader()
                                .AllowAnyMethod();
                      });
});

2. 网络与API绑定问题

  • 绑定地址限制:默认API可能仅绑定localhost,需修改app.Run()绑定所有网卡:
// 绑定所有可用IP的7214端口
app.Run("https://0.0.0.0:7214");
  • 防火墙拦截:在API所在电脑的Windows防火墙中添加入站规则,允许TCP协议的7214端口访问。
  • 连通性验证:在客户端电脑执行ping 192.168.100.60,确认两台电脑局域网互通。

3. HTTPS证书信任问题

若API使用自签名证书,客户端电脑会因证书不被信任拒绝请求:

  • 方案1:将API的自签名证书安装到客户端电脑的受信任的根证书颁发机构。
  • 方案2(仅开发环境测试):在客户端HttpClient中临时禁用证书验证:
async Task<bool> SendEmailToApi(string email)    
{
    try
    {
        var handler = new HttpClientHandler();
        // 临时禁用证书验证(开发环境用,生产环境禁止)
        handler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true;
        using (HttpClient client = new HttpClient(handler))    
        {
            // 后续请求代码不变...
        }
    }
    catch (Exception ex)
    {
        // 异常处理不变...
    }
}

4. API服务注册遗漏

Program.cs中缺少控制器服务注册,需添加:

// 在AddRazorPages之后添加
builder.Services.AddControllers();

测试验证

  1. 重启API服务,确认服务绑定到0.0.0.0:7214。
  2. 在客户端电脑用Postman测试https://192.168.100.60:7214/api/Email的POST请求,验证API可访问。
  3. 运行Windows Form客户端测试请求。

内容的提问来源于stack exchange,提问作者陳芸萱

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 23:25:36