ASP.NET 网站项目发布到远程 IIS,报错:
Web 部署任务失败。(已使用指定的进程(“Web Management Service”)连接到远程计算机,但未能验证服务器的证书。如果你信任该服务器,请再次连接并允许不信任的证书。 在以下位置了解更多信息: https://go.microsoft.com/fwlink/?LinkId=221672#ERROR_CERTIFICATE_VALIDATION_FAILED。) ...参照错误信息中的网址,在项目文件中添加该配置:
<PropertyGroup>
<AllowUntrustedCertificate>true</AllowUntrustedCertificate>
</PropertyGroup>问题复现
使用 .NET Framework 开发的网站项目,用 QQ 浏览器访问无法登录成功,用其它浏览器(如 Edge)没有问题。
只有访问 https 地址时出现问题。
原因
在 HTTPS 协议下,现代浏览器(特别是 QQ 浏览器)会强制执行安全策略。根据规范,当 Cookie 设置了 SameSite=None 时,必须同时设置 Secure 属性,否则浏览器会静默拒绝(丢弃)该 Cookie。
解决方案
方法一:如果您是通过 web.config 配置的,请确保 <system.web> 节点下的 <httpCookies> 设置正确,并且您的 .NET Framework 版本支持这些属性(4.7.2+)。
<system.web>
<httpCookies sameSite="None" requireSSL="true" />
<sessionState ... />
</system.web>方法二:在 Global.asax 文件的 Application_PostAuthenticateRequest 或 Application_EndRequest 事件中,强制为 Cookie 添加 Secure 属性。
protected void Application_PostAuthenticateRequest(object sender, EventArgs e)
{
// 仅在 HTTPS 环境下处理
if (Request.IsSecureConnection)
{
HttpCookie sessionCookie = Response.Cookies["ASP.NET_SessionId"];
if (sessionCookie != null)
{
// 强制设置 SameSite=None 和 Secure
sessionCookie.SameSite = SameSiteMode.None;
sessionCookie.Secure = true;
Response.Cookies.Set(sessionCookie);
}
}
}检验
确认 Set-Cookie 的值变为:
ASP.NET_SessionId=...; path=/; HttpOnly; SameSite=None; Secure方法一:打开 事件查看器-> Windows 日志-> 应用程序。

方法二:启用ASP.NET Core Module Stdout 日志。
修改网站根目录下的 web.config 文件,在 <aspNetCore> 节点中启用标准输出日志。你需要先手动创建 logs 文件夹并确保有写入权限。
<aspNetCore processPath="dotnet"
arguments=".\YourAppName.dll"
stdoutLogEnabled="true"
stdoutLogFile=".\logs\stdout"
hostingModel="inprocess" />重现错误后,即可在 logs 目录下查看生成的日志文件。注意:出于性能考虑,问题解决后建议将 stdoutLogEnabled 设为 false。
-
在 access_by_lua_block 代码块中实现远程鉴权:
#鉴权-START #resolver 223.5.5.5; # cat /etc/resolv.conf access_by_lua_block { local http = require("resty.http") local httpc = http.new() httpc:set_timeout(500) -- 连接超时 local res, err = httpc:request_uri("https://鉴权地址/", { method = "GET", headers = { ["X-Real-IP"] = ngx.var.remote_addr, ["User-Agent"] = ngx.var.http_user_agent, ["X-Forwarded-Host"] = ngx.var.host, ["X-Forwarded-Uri"] = ngx.var.request_uri, }, ssl_verify = false, -- 禁用 SSL 验证 timeout = 500, -- 读取超时 }) if not res then ngx.log(ngx.ERR, "Failed to request: " .. err) end if res and res.status == 403 then ngx.exit(ngx.HTTP_FORBIDDEN) -- return ngx.redirect("https://一个显示403友好信息的页面.html") end } #鉴权-END注意更改接口地址和友情显示 403 页面地址。
本示例仅捕获 403 状态码,500、408 等其它异常情况视为允许访问,请根据业务需求自行添加状态码的判断。
若超时也会进入
if not res then代码块。建议将此代码部署在 nginx 主配置文件的 http 代码块中(宝塔面板中的路径:/www/server/nginx/nginx/conf/nginx.conf),如果你只想为单个网站鉴权,也可以放在网站配置文件的 server 块中。
-
若鉴权接口在私网中,建议将鉴权接口域名和私网 IP 添加到 hosts 文件中。
附
-
直接输出字符串
ngx.header.content_type = "text/plain"; ngx.say("hello world!") -
输出到日志
ngx.log(ngx.ERR, "Response status: " .. res.status)日志在网站的 站名.error.log 中查看。
宝塔面板查看方式:日志 - 网站日志 - 异常
-
若想获取服务器 CPU 使用率等信息并传递给远程鉴权接口,请参考此文。
-
常见问题
no resolver defined to resolve
原因:没有定义 DNS 解析器
解决方法:在 http 块或 server 块中添加
resolver 8.8.8.8 valid=30s;,推荐使用接入商自己的公共 DNS,如果走内网,推荐使用本机 DNS。unable to get local issuer certificate
原因:没有配置 SSL 证书信息
解决方法:添加 request_uri 参数:
ssl_verify = true, -- 启用 SSL 验证 ssl_trusted_certificate = "证书路径", -- 指定 CA 证书路径或
ssl_verify = false, -- 禁用 SSL 验证 -
若您不想用 lua,可以用 nginx 原生自带的 auth_request 模块来实现。
-
若 WAF 返回拒绝访问时需要 302 跳转(即 return ngx.redirect(...)),那么最好加上禁止缓存的标识,防止 CDN 污染:
if res and res.status == 403 then -- ===== 禁止 CDN 缓存此响应 ===== ngx.header["Cache-Control"] = "no-store, no-cache, must-revalidate, proxy-revalidate" ngx.header["Pragma"] = "no-cache" ngx.header["Expires"] = "0" -- 可选:添加标记头,方便调试 ngx.header["X-WAF-Action"] = "blocked" return ngx.redirect("https://...") end
POST
$.post('AjaxCases', {
following: true,
success: null,
page: 1,
}, function (response) {
console.log(response.data)
}, 'json').fail(function (xhr, status, error) {
console.log(xhr.responseText);
});[HttpPost]
public IActionResult AjaxCases([FromForm] AjaxCasesRequestModel req)
{
bool? following = req.following;
bool? success = req.success;
int page = req.page;
}提示:只能传输对象(Object),不能传输数组(Array)。
SignalR 是一个开源的实时通信库,用于构建实时 Web 应用程序。它提供了一个简单的 API,可以在客户端和服务器之间建立持久连接,以便实时地推送数据。
与传统的 WebSocket 相比,SignalR 提供了更高级的功能和更简单的开发体验。下面是一些主要区别:
支持多种传输方式:SignalR 可以使用多种传输方式,包括 WebSocket、Server-Sent Events(SSE)、长轮询和 Forever Frame。这使得 SignalR 在不同的环境中都能提供实时通信的能力,即使某些浏览器不支持 WebSocket,也可以使用其他传输方式。
自动处理连接管理:SignalR 管理连接的生命周期,包括连接的建立、断开和重新连接。它会自动处理连接的失败和重新连接的逻辑,简化了开发人员的工作。
服务器端推送:SignalR 允许服务器端主动推送消息给客户端,而不需要客户端发起请求。这使得实时通信变得更加高效和实时,适用于聊天应用、实时监控等场景。
跨平台支持:SignalR 可以在多个平台上使用,包括 .NET、Java、JavaScript 等。这使得开发人员可以使用自己熟悉的语言和框架来构建实时应用程序。
微软官方提供了针对 ASP.NET Core Web 应用(Razor 页面)的详细教程,这里给出 MVC 版本入门教程。
最终将创建一个正常运行的聊天应用:

创建 Web 应用项目


添加 SignalR 客户端库
在“解决方案资源管理器”>中,右键单击项目,然后选择“添加”“客户端库”。
在“添加客户端库”对话框中:
“提供程序”选择“unpkg”
“库”,请输入 @microsoft/signalr@latest。
选择“选择特定文件”,展开“dist/browser”文件夹,然后选择 signalr.js 和 signalr.min.js。
点击“安装” 。

创建 SignalR Hubs 类
using Microsoft.AspNetCore.SignalR;
/// <summary>
/// Hub 类管理连接、组和消息
/// </summary>
public class ChatHub : Hub
{
/// <summary>
/// 可通过已连接客户端调用 SendMessage,以向所有客户端发送消息
/// </summary>
public async Task SendMessage(string user, string message)
{
// Clients.All 向所有的客户端发送消息
// ReceiveMessage 是客户端监听的方法
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}其父类 Hub 可管理连接、组和消息。这里演示的是向所有客户端发送消息。
配置 SignalR
打开 Program.cs,添加注入:
builder.Services.AddSignalR();添加路由:
app.MapHub<ChatHub>("/chatHub");添加 SignalR 客户端代码
视图页面:
<div class="container">
<div class="row p-1">
<div class="col-1">用户</div>
<div class="col-5"><input type="text" id="userInput" /></div>
</div>
<div class="row p-1">
<div class="col-1">消息</div>
<div class="col-5"><input type="text" class="w-100" id="messageInput" /></div>
</div>
<div class="row p-1">
<div class="col-6 text-end">
<input type="button" id="sendButton" value="发送消息" />
</div>
</div>
<div class="row p-1">
<div class="col-6">
<hr />
</div>
</div>
<div class="row p-1">
<div class="col-6">
<ul id="messagesList"></ul>
</div>
</div>
</div>
<script src="~/lib/microsoft/signalr/dist/browser/signalr.min.js"></script>
<script src="~/js/chat.js"></script>chat.js 文件:
"use strict";
var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();
// 在连接建立之前禁用发送按钮
document.getElementById("sendButton").disabled = true;
connection.on("ReceiveMessage", function (user, message) {
var li = document.createElement("li");
document.getElementById("messagesList").appendChild(li);
// 修改此处时应注意脚本注入问题
li.textContent = `${user} says ${message}`;
});
connection.start().then(function () {
document.getElementById("sendButton").disabled = false;
}).catch(function (err) {
return console.error(err.toString());
});
document.getElementById("sendButton").addEventListener("click", function (event) {
var user = document.getElementById("userInput").value;
var message = document.getElementById("messageInput").value;
connection.invoke("SendMessage", user, message).catch(function (err) {
return console.error(err.toString());
});
event.preventDefault();
});完成。在线示例:https://xoyozo.net/Demo/SignalRDemo
推荐使用 SignalR 来平替 WebSocket,参考教程。
【服务端(.NET)】
一、创建 WebSocketHandler 类,用于处理客户端发送过来的消息,并分发到其它客户端
public class WebSocketHandler
{
private static List<WebSocket> connectedClients = [];
public static async Task Handle(WebSocket webSocket)
{
connectedClients.Add(webSocket);
byte[] buffer = new byte[1024];
WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
while (!result.CloseStatus.HasValue)
{
string message = Encoding.UTF8.GetString(buffer, 0, result.Count);
Console.WriteLine($"Received message: {message}");
// 处理接收到的消息,例如广播给其他客户端
await BroadcastMessage(message, webSocket);
result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
}
connectedClients.Remove(webSocket);
await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
}
private static async Task BroadcastMessage(string message, WebSocket sender)
{
foreach (var client in connectedClients)
{
if (client != sender && client.State == WebSocketState.Open)
{
await client.SendAsync(Encoding.UTF8.GetBytes(message), WebSocketMessageType.Text, true, CancellationToken.None);
}
}
}
}
二、在 Program.cs 或 Startup.cs 中插入:
// 添加 WebSocket 路由
app.UseWebSockets();
app.Use(async (context, next) =>
{
if (context.Request.Path == "/chat")
{
if (context.WebSockets.IsWebSocketRequest)
{
WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();
await WebSocketHandler.Handle(webSocket);
}
else
{
context.Response.StatusCode = 400;
}
}
else
{
await next();
}
});
这里的路由路径可以更改,此处将会创建一个 WebSocket 连接,并将其传递给 WebSocketHandler.Handle 方法进行处理。
也可以用控制器来接收 WebSocket 消息。
【客户端(JS)】
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" />
<title>WebSocket 示例(JS + ASP.NET)</title>
<style>
#list { width: 100%; max-width: 500px; }
.tip { color: red; }
</style>
</head>
<body>
<h2>WebSocket 示例(JS + ASP.NET)</h2>
<textarea id="list" readonly rows="20"></textarea>
<div>
<input type="text" id="msg" />
<button onclick="fn_send()">发送</button>
<button onclick="fn_disconnect()">断开</button>
</div>
<p id="tip_required">请输入要发送的内容</p>
<p id="tip_closed">WebSocket 连接未建立</p>
<script>
var wsUrl = "wss://" + window.location.hostname + ":" + window.location.port + "/chat";
var webSocket;
var domList = document.getElementById('list');
// 初始化 WebSocket 并连接
function fn_ConnectWebSocket() {
webSocket = new WebSocket(wsUrl);
// 向服务端发送连接请求
webSocket.onopen = function (event) {
var content = domList.value;
content += "[ WebSocket 连接已建立 ]" + '\r\n';
domList.innerHTML = content;
document.getElementById('tip_closed').style.display = 'none';
webSocket.send(JSON.stringify({
msg: 'Hello'
}));
};
// 接收服务端发送的消息
webSocket.onmessage = function (event) {
if (event.data) {
var content = domList.value;
content += event.data + '\r\n';
domList.innerHTML = content;
domList.scrollTop = domList.scrollHeight;
}
};
// 各种情况导致的连接关闭或失败
webSocket.onclose = function (event) {
var content = domList.value;
content += "[ WebSocket 连接已关闭,3 秒后自动重连 ]" + '\r\n';
domList.innerHTML = content;
document.getElementById('tip_closed').style.display = 'block';
setTimeout(function () {
var content = domList.value;
content += "[ 正在重连... ]" + '\r\n';
domList.innerHTML = content;
fn_ConnectWebSocket();
}, 3000); // 3 秒后重连
};
}
// 检查连接状态
function fn_IsWebSocketConnected() {
if (webSocket.readyState === WebSocket.OPEN) {
document.getElementById('tip_closed').style.display = 'none';
return true;
} else {
document.getElementById('tip_closed').style.display = 'block';
return false;
}
}
// 发送内容
function fn_send() {
if (fn_IsWebSocketConnected()) {
var message = document.getElementById('msg').value;
document.getElementById('tip_required').style.display = message ? 'none' : 'block';
if (message) {
webSocket.send(JSON.stringify({
msg: message
}));
}
}
}
// 断开连接
function fn_disconnect() {
if (fn_IsWebSocketConnected()) {
// 部分浏览器调用 close() 方法关闭 WebSocket 时不支持传参
// webSocket.close(001, "Reason");
webSocket.close();
}
}
// 执行连接
fn_ConnectWebSocket();
</script>
</body>
</html>
【在线示例】
https://xoyozo.net/Demo/JsNetWebSocket
【其它】
-
服务端以 IIS 作为 Web 服务器,那么需要安装 WebSocket 协议
-
一个连接对应一个客户端(即 JS 中的 WebSocket 对象),注意与会话 Session 的区别
-
在实际项目中使用应考虑兼容性问题
-
程序设计应避免 XSS、CSRF 等安全隐患
-
参考文档:https://learn.microsoft.com/zh-cn/aspnet/core/fundamentals/websockets
客户端:Failed to connect to host.
服务端:无任何日志
原因:可能是域名、IP 或端口有误,或端口未开放。
客户端/服务端:530 Login incorrect.
原因:用户名或密码错误。
客户端/服务端:503 Use AUTH first.
原因:服务端开启了 FTPS 协议(FTP over TLS),且禁止了 FTP 协议(plain FTP)。
解决方法:不建议服务端恢复不安全的 FTP 协议,客户端应配置 client.Config 的 EncryptionMode、DataConnectionEncryption、SslProtocols、ValidateCertificate 等参数。
客户端/服务端:530 This server does not allow plain FTP. You have to use FTP over TLS.
原因:服务端启用了 FTPS。
解决方法:给 client.Config.EncryptionMode 正确的赋值(FtpEncryptionMode.Explicit 或 FtpEncryptionMode.Auto)。
服务端:[Error] TLS session of data connection not resumed.
原因:证书版本有误。
解决方法:给 client.Config.SslProtocols 赋值正确的 TLS 版本。
服务端:521 PROT P required
原因:服务端开启了“Require TLS session resumption on data connection when using PROT P”
解决方法:client.Config.DataConnectionEncryption = true;
客户端/服务端:450 TLS session of data connection has not resumed or the session does not match the control connection
原因:TLS 与控制连接不匹配,即服务端开启了“Require TLS session resumption on data connection when using PROT P”
解决方法:我暂时还不知道原因,临时关闭了“Require TLS session resumption on data connection when using PROT P”(不建议)。该问题出现在 FileZilla Server 0.x 版本,在 1.x 版本中没有该配置选项。
在 Vue 中,当你将一个布尔对象双向绑定到 radio 输入上时,确保 radio 的 value 属性仍然保持布尔类型是很重要的。如果 value 属性是字符串,那么 Vue 会将其解释为字符串而不是布尔值。以下是一个示例,演示如何正确地将布尔对象双向绑定到 radio 按钮,并确保 value 属性保持布尔类型:
<template>
<div>
<input type="radio" v-model="myBoolean" :value="true" /> True
<input type="radio" v-model="myBoolean" :value="false" /> False
<p>myBoolean: {{ myBoolean }}</p>
</div>
</template>
<script>
export default {
data() {
return {
myBoolean: false, // 布尔对象
};
},
};
</script>在这个示例中,我们使用了 v-model 指令将 myBoolean 属性与两个 radio 按钮进行了双向绑定。通过将 value 属性设置为 true 和 false,我们确保了 myBoolean 属性保持布尔类型。
这样,当用户选择其中一个 radio 按钮时,myBoolean 属性将保持布尔值而不是字符串。确保 value 属性的类型与要绑定的数据类型匹配,以确保绑定的数据类型保持一致。
同样的问题出现在 select 上也是一样:
<select v-model="cat.colorId" required>
<option :value="null">不选择</option>
<option v-for="color in colors" :value="color.id">{{color.name}}</option>
</select>