Azure上.NET Framework4.5 Web API如何检测请求的TLS协商版本?
在.NET Framework 4.5中检测API请求的协商TLS版本
可以在.NET Framework 4.5的Web API中检测单个请求协商的TLS版本,核心是通过ASP.NET的HttpContext获取请求的服务器变量。以下是修改后的接口代码,添加了TLS版本的获取与日志记录逻辑:
[HttpGet] [Authorize(Roles = "User")] public HttpResponseMessage GetFirstName() { // 获取并记录协商的TLS版本 string tlsVersion = null; if (HttpContext.Current != null && HttpContext.Current.Request != null) { // 仅HTTPS请求会返回该变量 tlsVersion = HttpContext.Current.Request.ServerVariables["CERT_PROTOCOL"]; // 写入日志(可替换为你的日志组件,如log4net、NLog等) System.Diagnostics.Trace.WriteLine($"用户 {User.Identity.GetUserName()} 请求使用的TLS版本: {tlsVersion ?? "非HTTPS请求"}"); } var email = User.Identity.GetUserName(); ApplicationUser userFound = GetUserByEmail(email); if (userFound == null) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Error: No such user."); } var firstName = new { FirstName = userFound.FirstName }; return Request.CreateResponse(HttpStatusCode.OK, firstName); }
关键说明
CERT_PROTOCOL是ASP.NET提供的服务器变量,仅当请求通过HTTPS访问时会返回协商的协议字符串,格式如TLS/1.0、TLS/1.1、TLS/1.2。- 若请求为HTTP,该变量会返回
null,需做空值判断避免异常。 - 日志部分可根据实际项目的日志框架替换(比如用
Logger.Info()替代Trace.WriteLine()),方便后续统计分析不同TLS版本的请求占比。
补充提示
如果需要批量收集所有请求的TLS版本,也可以在Global.asax的Application_BeginRequest事件中统一处理,无需在每个接口中重复写代码:
protected void Application_BeginRequest() { if (HttpContext.Current != null && HttpContext.Current.Request.IsSecureConnection) { string tlsVersion = HttpContext.Current.Request.ServerVariables["CERT_PROTOCOL"]; System.Diagnostics.Trace.WriteLine($"请求路径: {HttpContext.Current.Request.Path}, TLS版本: {tlsVersion}"); } }
内容的提问来源于stack exchange,提问作者IMSsam
相关产品推荐
相关产品推荐

