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

Blazor Server端CSP配置引发连接拒绝错误,如何修复?

Blazor Server项目CSP配置导致连接错误的修复方案

问题背景

我有一个Blazor Server端项目,添加了以下meta标签配置:

<meta http-equiv="Content-Security-Policy" 
      content="base-uri 'self';
               default-src 'self';
               img-src data: https:;
               object-src 'none';
               script-src 'self';
               style-src 'self' 'unsafe-inline';
               upgrade-insecure-requests;">

现在出现两类错误:

Refused to connect to 'http://localhost:58126/c5f3e2f1da1843188844fd8515c3ca3b/browserLinkSignalR/negotiate?requestUrl=https%3A%2F%2Flocalhost%3A44350%2FDashboard&browserName=&userAgent=Mozilla%2F5.0+(Windows+NT+10.0%3B+Win64%3B+x64)+AppleWebKit%2F537.36+(KHTML%2C+like+Gecko)+Chrome%2F109.0.0.0+Safari%2F537.36&browserIdKey=window.browserLink.initializationData.browserId&browserId=2655-11e6&clientProtocol=1.3&_=1675268211057' because it violates the following Content Security Policy directive: "default-src 'self'". Note that 'connect-src' was not explicitly set, so 'default-src' is used as a fallback.

以及

Refused to connect to 'wss://localhost:44393/KeyAccount.Web/' because it violates the following Content Security Policy directive: "default-src 'self'". Note that 'connect-src' was not explicitly set, so 'default-src' is used as a fallback.

修复方案

这两个错误的核心是未显式配置connect-src指令,浏览器默认用default-src 'self'作为 fallback,但Blazor Server的SignalR连接、Visual Studio的BrowserLink需要额外的连接源权限。

1. 显式添加connect-src指令

修改CSP配置,添加connect-src并包含必要的连接源:

  • 'self':允许同源连接
  • 报错中的两个本地地址:http://localhost:58126和wss://localhost:44393

修改后的配置示例:

<meta http-equiv="Content-Security-Policy" 
      content="base-uri 'self';
               default-src 'self';
               img-src data: https:;
               object-src 'none';
               script-src 'self';
               style-src 'self' 'unsafe-inline';
               connect-src 'self' http://localhost:58126 wss://localhost:44393;
               upgrade-insecure-requests;">

2. 简化开发环境配置(可选)

如果开发时端口经常变动,可用通配符覆盖本地连接需求:

connect-src 'self' http://localhost:* wss://localhost:*;

注意:生产环境必须替换为具体的域名/端口,避免扩大安全风险。

3. 禁用BrowserLink(可选)

如果不需要Visual Studio的BrowserLink功能,直接关闭即可省去对应CSP规则配置:

  • 在Visual Studio工具栏,点击「Browser Link」按钮(刷新图标旁的下拉菜单),选择「Disable Browser Link」

内容的提问来源于stack exchange,提问作者Ivan-Mark Debono

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 06:45:36