如何在C#应用中接收浏览器扩展JS发送的POST请求数据
C# 接收浏览器扩展POST请求实现方案
前置修正(JS侧)
你当前提供的JS代码中POST目标地址缺少斜杠,需要调整为http://localhost:9812/,否则会触发请求错误。
C# 代码实现(基于系统内置HttpListener,无第三方依赖)
该方案轻量无需额外安装依赖,适配本地跨进程通信场景:
using System; using System.IO; using System.Net; using System.Text; class LocalHttpServer { private static HttpListener _listener; private const string ListenUrl = "http://localhost:9812/"; static void Main(string[] args) { // 初始化监听器 _listener = new HttpListener(); _listener.Prefixes.Add(ListenUrl); _listener.Start(); Console.WriteLine($"服务已启动,正在监听 {ListenUrl}"); // 异步处理请求,避免阻塞 _listener.BeginGetContext(OnRequestReceived, null); Console.ReadLine(); // 退出时释放资源 _listener.Stop(); _listener.Close(); } private static void OnRequestReceived(IAsyncResult ar) { if (!_listener.IsListening) return; var context = _listener.EndGetContext(ar); // 继续监听下一个请求 _listener.BeginGetContext(OnRequestReceived, null); var request = context.Request; var response = context.Response; // 处理跨域:允许所有来源访问,适配浏览器扩展请求 response.AddHeader("Access-Control-Allow-Origin", "*"); response.AddHeader("Access-Control-Allow-Methods", "POST, OPTIONS"); response.AddHeader("Access-Control-Allow-Headers", "Content-Type"); // 处理浏览器预检请求 if (request.HttpMethod == "OPTIONS") { response.StatusCode = (int)HttpStatusCode.OK; response.Close(); return; } // 处理POST请求,读取提交的URL数据 if (request.HttpMethod == "POST") { using var reader = new StreamReader(request.InputStream, Encoding.UTF8); string receivedUrl = reader.ReadToEnd(); // 这里写你自己的业务逻辑,比如打印、存储收到的URL Console.WriteLine($"收到浏览器扩展提交的地址:{receivedUrl}"); // 返回响应 response.StatusCode = (int)HttpStatusCode.OK; byte[] respBuffer = Encoding.UTF8.GetBytes("接收成功"); response.OutputStream.Write(respBuffer, 0, respBuffer.Length); } else { response.StatusCode = (int)HttpStatusCode.MethodNotAllowed; } response.Close(); } }
注意事项
- 首次运行如果报权限错误,可用管理员身份启动程序,或者执行命令
netsh http add urlacl url=http://localhost:9812/ user=你的Windows用户名为当前用户授权端口监听权限 - 如果你使用的是WPF/WinForm等桌面应用,把服务逻辑放到后台线程运行即可,避免阻塞UI
- 如果需要更高的性能或更复杂的路由逻辑,也可以改用ASP.NET Core Minimal API实现,基础逻辑和上述方案一致
内容的提问来源于stack exchange,提问作者AquaTheGoddess
相关产品推荐
相关产品推荐

